List of usage examples for org.w3c.dom Node getParentNode
public Node getParentNode();
From source file:de.betterform.xml.xforms.model.submission.Submission.java
private void updateInstanceAndModel(Model referedModel, Document responseInstance) throws XFormsException { if (this.targetExpr != null) { Node targetNode; if (this.instance == null) targetNode = XPathUtil.getAsNode(XPathCache.getInstance().evaluate(evalInScopeContext(), 1, this.targetExpr, this.prefixMapping, this.xpathFunctionContext), 1); else {//from w w w . ja v a 2 s. c o m targetNode = XPathUtil.getAsNode(XPathCache.getInstance().evaluate( referedModel.getInstance(this.instance).getRootContext().getNodeset(), 1, this.targetExpr, this.prefixMapping, this.xpathFunctionContext), 1); } if (targetNode != null && targetNode.getNodeType() == Node.ELEMENT_NODE) { targetNode.getParentNode().replaceChild( targetNode.getOwnerDocument().importNode(responseInstance.getDocumentElement(), true), targetNode); } else if (targetNode != null && targetNode.getNodeType() == Node.ATTRIBUTE_NODE) { if (LOGGER.isDebugEnabled()) { DOMUtil.prettyPrintDOM(responseInstance); } // targetNode.setContent(responseInstance.getTextContent()); String attrValue = responseInstance.getDocumentElement().getTextContent(); targetNode.setNodeValue(attrValue); } else { throw new XFormsSubmitError("Invalid target", this.getTarget(), XFormsSubmitError.constructInfoObject(this.element, this.container, locationPath, XFormsConstants.TARGET_ERROR, getResourceURI(), 200d, null, "", "")); } } else if (this.instance != null && referedModel.getInstance(this.instance) == null) { this.container.dispatch(referedModel.getId(), XFormsEventNames.BINDING_EXCEPTION); // throw new XFormsBindingException("invalid instance id at " + DOMUtil.getCanonicalPath(this.getElement()), this.target, this.instance); } else if (this.instance != null) { referedModel.getInstance(this.instance).setInstanceDocument(responseInstance); } else { referedModel.getInstance(getInstanceId()).setInstanceDocument(responseInstance); } // perform rebuild, recalculate, revalidate, and refresh referedModel.rebuild(); referedModel.recalculate(); referedModel.revalidate(); }
From source file:com.smartbear.jenkins.plugins.testcomplete.TcLogParser.java
private void processProject(ZipFile logArchive, Node rootOwnerNode, Node rootOwnerNodeInfoSummary, XMLStreamWriter writer) throws ParsingException, XMLStreamException { String totalTests = NodeUtils.getTextProperty( NodeUtils.findNamedNode(rootOwnerNodeInfoSummary.getChildNodes(), "total"), "total (sum)"); String failedTests = NodeUtils.getTextProperty( NodeUtils.findNamedNode(rootOwnerNodeInfoSummary.getChildNodes(), "failed"), "total (sum)"); long startDate = Utils.safeConvertDate(NodeUtils.getTextProperty(rootOwnerNodeInfoSummary, "start date")); long stopDate = Utils.safeConvertDate(NodeUtils.getTextProperty(rootOwnerNodeInfoSummary, "stop date")); long projectDuration = stopDate - startDate > 0 ? stopDate - startDate : 0; String projectName = NodeUtils.getTextProperty(rootOwnerNodeInfoSummary, "test"); Calendar cal = new GregorianCalendar(); cal.setTimeInMillis(startDate);// w w w. j a v a2 s . c o m String timestamp = DatatypeConverter.printDateTime(cal); String rootOwnerNodeFileName = NodeUtils.getTextProperty(rootOwnerNode, "filename"); if (rootOwnerNodeFileName == null || rootOwnerNodeFileName.isEmpty()) { throw new ParsingException("Unable to obtain filename for project node."); } List<Pair<String, Node>> items = null; try { items = NodeUtils.findChildNodesRecursively(logArchive, rootOwnerNode, rootOwnerNode.getParentNode().getChildNodes(), ""); } catch (Exception e) { items = new ArrayList<Pair<String, Node>>(); } writer.writeStartElement("testsuite"); writer.writeAttribute("name", projectName); writer.writeAttribute("failures", failedTests); writer.writeAttribute("tests", totalTests); writer.writeAttribute("time", Double.toString(projectDuration / 1000f)); writer.writeAttribute("timestamp", timestamp); for (Pair<String, Node> pair : items) { processItem(logArchive, pair.getValue(), projectName, writer, pair.getKey()); } writer.writeEndElement(); //testcase }
From source file:edu.uams.clara.webapp.xml.processor.impl.DefaultXmlProcessorImpl.java
private Document replaceIfExistingByXPaths(final Document originalDom, final Document modifiedDom, Map<String, String> xPathPairs) throws XPathExpressionException { Document finalDom = originalDom; Element finalDomRoot = (Element) finalDom.getFirstChild(); //Element modifiedDomRoot = (Element) modifiedDom.getFirstChild(); Element lastChild = null;//from w ww. j av a2 s . c om for (Entry<String, String> xPathPair : xPathPairs.entrySet()) { /** * basically, this is to copy the element specified in srcXPath, and * replace/add it to the position pointed by destXPath... */ String srcXPath = xPathPair.getKey(); logger.debug("srcXPath: " + srcXPath); String destXPath = xPathPair.getValue(); logger.debug("destXPath: " + destXPath); XPath xPath = getXPathInstance(); // find all the nodes specified by destXPath in the originalDom, and // delete them all NodeList existingNodeList = (NodeList) (xPath.evaluate(destXPath, finalDom, XPathConstants.NODESET)); xPath.reset(); // find all the nodes specified by srcXPath in the modifiedDom NodeList nodeList = (NodeList) (xPath.evaluate(srcXPath, modifiedDom, XPathConstants.NODESET)); int el = existingNodeList.getLength(); logger.debug("find '" + el + "' in originalDom using xPath: " + destXPath); int l = nodeList.getLength(); logger.debug("find '" + l + "' in modifiedXml using xPath: " + srcXPath); for (int i = 0; i < el; i++) { Node c = existingNodeList.item(i); //xPathExpression = xPath.compile(srcXPath); //NodeList srcNodeLst = (NodeList) (xPathExpression.evaluate( //modifiedDom, XPathConstants.NODESET)); //NodeList srcNodeLst = modifiedDomRoot.getElementsByTagName(c.getNodeName()); if (l > 0) { // remove this node from its parent... c.getParentNode().removeChild(c); logger.debug("Node:" + c.getNodeName() + " is removed!"); } } // create the node structure first. and return the last child of the // path... the right most node... lastChild = createElementStructureByPath(finalDomRoot, destXPath); List<String> nodeNameList = getNodeList(destXPath); String lastNodeName = nodeNameList.get(nodeNameList.size() - 1); Node currentNode = null; for (int i = 0; i < l; i++) { currentNode = nodeList.item(i); // the name of the last node in srcXPath might not be the same // as the name of the last node in destXPath Element lastElement = finalDom.createElement(lastNodeName); // NodeList currentNodeChildNodes = currentNode.getChildNodes(); // int s = currentNodeChildNodes.getLength(); // for(int j = 0; j < s; j++){ // lastElement.appendChild(finalDom.importNode(currentNodeChildNodes.item(j), // true)); // } if (currentNode.hasAttributes()) { NamedNodeMap attributes = currentNode.getAttributes(); for (int j = 0; j < attributes.getLength(); j++) { String attribute_name = attributes.item(j).getNodeName(); String attribute_value = attributes.item(j).getNodeValue(); lastElement.setAttribute(attribute_name, attribute_value); } } while (currentNode.hasChildNodes()) { Node kid = currentNode.getFirstChild(); currentNode.removeChild(kid); lastElement.appendChild(finalDom.importNode(kid, true)); } lastChild.appendChild(lastElement); } } return finalDom; }
From source file:com.mtgi.analytics.XmlBehaviorEventPersisterTest.java
@Test public void testNestedEvents() throws InterruptedException, IOException, XMLStreamException, SAXException { //we reuse the test event creation code from jdbc persister test to get ourselves an interesting dataset. final ArrayList<BehaviorEvent> events = new ArrayList<BehaviorEvent>(); int[] counter = { 0 }; for (int i = 0; i < 3; ++i) JdbcBehaviorEventPersisterTest.createEvent(null, 1, 3, 3, counter, events); LinkedList<BehaviorEvent> queue = new LinkedList<BehaviorEvent>(events); persister.persist(queue);// w ww . j a v a 2 s. c o m assertEquals("queue unmodified by persistence operation", 39, queue.size()); assertEquals("persister reports correct file size", file.length(), persister.getFileSize()); //now perform verification of log data against the expected results. String fileName = persister.rotateLog(); Document actualXML = buildTestDocument(FileUtils.readFileToString(new File(fileName))); //read up the expected results for comparison. InputStream expectedData = XmlBehaviorEventPersisterTest.class .getResourceAsStream("XmlBehaviorEventPersisterTest.testNestedEvents-result.xml"); Document controlXML = buildTestDocument(new InputSource(expectedData)); expectedData.close(); XMLUnit.setIgnoreWhitespace(true); //compare the logged data to our expectations, ignoring time-sensitive values. Diff diff = new Diff(controlXML, actualXML); diff.overrideDifferenceListener(new DifferenceListener() { //filter out artificial differences in id, start time, duration public int differenceFound(Difference diff) { Node cn = diff.getControlNodeDetail().getNode(); Node tn = diff.getTestNodeDetail().getNode(); if (cn != null && tn != null) { short ctype = cn.getNodeType(); short ttype = tn.getNodeType(); if (ctype == ttype) { if (ctype == Node.ATTRIBUTE_NODE) { if (cn.getNodeName().equals("id") || cn.getNodeName().equals("parent-id")) { //we can at least verify that the logged ID matches the ID assigned to our data model. int index = -1; for (Node n = ((Attr) cn).getOwnerElement(); n != null; n = n.getPreviousSibling()) if (n.getNodeType() == Node.ELEMENT_NODE) ++index; BehaviorEvent event = events.get(index); if (cn.getNodeName().equals("id")) { assertEquals("logged event has same id as data model", event.getId().toString(), tn.getNodeValue()); } else { BehaviorEvent parent = event.getParent(); assertNotNull("node " + event.getId() + " has parent", parent); assertEquals("logged event has same parent-id as data model", parent.getId().toString(), tn.getNodeValue()); } return RETURN_IGNORE_DIFFERENCE_NODES_SIMILAR; } } else if (ctype == Node.TEXT_NODE) { String cname = cn.getParentNode().getNodeName(); String tname = tn.getParentNode().getNodeName(); if (cname.equals(tname)) { //TODO: sanity check values. if ("duration-ns".equals(cname) || "start".equals(cname)) return RETURN_IGNORE_DIFFERENCE_NODES_SIMILAR; } } } } return RETURN_ACCEPT_DIFFERENCE; } public void skippedComparison(Node n0, Node n1) { } }); if (!diff.similar()) fail(diff.appendMessage(new StringBuffer()).toString()); }
From source file:it.imtech.metadata.MetaUtility.java
private void metadata_reader_metadatas(Element iENode, TreeMap<Object, Metadata> metadatas, boolean forceAdd, TreeMap forceAddMID, String sLang) { try {/*from w w w .ja v a 2 s . c o m*/ if (iENode.getTagName().equals("metadatas")) { NodeList nList = iENode.getChildNodes(); for (int s = 0; s < nList.getLength(); s++) { if (nList.item(s).getNodeType() == Node.ELEMENT_NODE) { Element iInnerNode = (Element) nList.item(s); if (iInnerNode.getTagName().equals("metadata")) { String MID = iInnerNode.getAttribute("ID"); //Se hidden rimuovo l'elemento dai forzati String hidden = "0"; if (iInnerNode.hasAttribute("hidden")) { hidden = iInnerNode.getAttribute("hidden"); forceAddMID.remove(iInnerNode.getAttribute("ID")); } if (forceAddMID.containsKey(MID)) { forceAdd = true; } String MID_parent = iInnerNode.getAttribute("mid_parent"); String mandatory = iInnerNode.getAttribute("mandatory"); String datatype = iInnerNode.getAttribute("datatype"); String editable = iInnerNode.getAttribute("editable"); String foxmlname = iInnerNode.getAttribute("forxmlname"); String sequence = iInnerNode.getAttribute("sequence"); String sequencemulti = ""; if (MID_parent.equals("22") || MID_parent.equals("45")) { Node searchparent = iInnerNode; boolean found = false; while (!found) { Element x = (Element) searchparent.getParentNode(); if (x.getAttribute("ID").equals("22")) { sequencemulti = x.getAttribute("sequence"); found = true; } else { searchparent = searchparent.getParentNode(); } } } //Add contributors management if (MID_parent.equals("11") || MID_parent.equals("13")) { Node searchparent = iInnerNode; boolean found = false; while (!found) { Element x = (Element) searchparent.getParentNode(); if (x.getAttribute("ID").equals("11")) { sequencemulti = x.getAttribute("sequence"); found = true; } else { searchparent = searchparent.getParentNode(); } } } if (MID.equals("11")) { Element x = (Element) iInnerNode; sequencemulti = x.getAttribute("sequence"); } String foxmlnamespace = iInnerNode.getAttribute("fornamespace"); if (!metadata_namespaces.containsValue(foxmlnamespace)) { int count = metadata_namespaces.size(); count++; metadata_namespaces.put("ns" + count, foxmlnamespace); } String description = null; String DESCRIPTION_DE = null; TreeMap<Object, Metadata> submetadatas = new TreeMap<Object, Metadata>(); NodeList innerList = iInnerNode.getChildNodes(); for (int z = 0; z < innerList.getLength(); z++) { if (innerList.item(z).getNodeType() == Node.ELEMENT_NODE) { Element iDescrNode = (Element) innerList.item(z); if (iDescrNode.getAttribute("isocode").equals(sLang)) { description = iDescrNode.getTextContent(); } else if (iDescrNode.getAttribute("isocode").equals("de")) { DESCRIPTION_DE = iDescrNode.getTextContent(); } if (iDescrNode.getTagName().equals("metadatas")) { if (MID.equals("98")) { metadata_reader_metadatas(iDescrNode, submetadatas, true, forceAddMID, sLang); } else { metadata_reader_metadatas(iDescrNode, submetadatas, false, forceAddMID, sLang); } } } } //Fallback DE if (description == null) { description = DESCRIPTION_DE; } if (description == null && !iInnerNode.getTagName().equals("metadata")) { throw new Exception( "Can't find description for metadata " + iInnerNode.getTagName()); } if ((mandatory.equals("Y") || forceAdd == true)) { int mid_parent = 0; if (!MID_parent.equals("")) { mid_parent = Integer.parseInt(MID_parent); } Metadata t = new Metadata(Integer.parseInt(MID), mid_parent, description, datatype, editable, foxmlname, null, foxmlnamespace, mandatory, hidden, sequencemulti); t.submetadatas = submetadatas; String index = sequence; if (index == null || index.equals("")) { index = MID; } int param = Integer.parseInt(index); metadatas.put(param, t); } if (forceAddMID.containsKey(MID.toString())) { forceAdd = false; } } } } } } catch (Exception ex) { logger.error(ex.getMessage()); } }
From source file:eu.europa.esig.dss.xades.validation.XAdESSignature.java
/** * Checks if the given {@code Element} has as parent the current signature. This is the security check. * * @param element/* w w w . ja v a2s . c om*/ * the element to be checked (can be null) * @return true if the given element has as parent the current signature element, false otherwise */ private boolean hasSignatureAsParent(final Element element) { if (element == null) { return false; } Node node = element; String nodeName = node.getNodeName(); if (XPathQueryHolder.XMLE_X509CERTIFICATE.equals(nodeName)) { node = node.getParentNode(); if (node == null) { return false; } nodeName = node.getNodeName(); } if (XPathQueryHolder.XMLE_X509DATA.equals(nodeName)) { node = node.getParentNode(); if (node == null) { return false; } nodeName = node.getNodeName(); } if (XPathQueryHolder.XMLE_KEYINFO.equals(nodeName)) { node = node.getParentNode(); if (node == null) { return false; } } if (!node.equals(signatureElement)) { return false; } return true; }
From source file:de.betterform.connector.ModelSubmissionHandler.java
/** * Purpose:<br/>/*w w w . j a va 2 s . com*/ * The ModelSubmissionHandler can be used to exchange data between XForms models. It is capable of replacing data * in a certain instance of the receiver model.<br/><br/> * * Syntax: model:[Model ID]#instance('[Instance ID]')/[XPath]<br/><br/> * * Caveats:<br/> * - Model and Instance IDs must be known to allow explicit addressing<br/> * - the form author has to make sure that no ID collisions take place<br/> * - the XPath must be explicitly given even if the the target Node is the root Node of the instance * * * @param submission the submission issuing the request. * @param instance the instance data to be serialized and submitted. * @return * @throws de.betterform.xml.xforms.exception.XFormsException * if any error occurred during submission. */ public Map submit(Submission submission, Node instance) throws XFormsException { try { String replaceMode = submission.getReplace(); if (!(replaceMode.equals("none") || replaceMode.equals("instance"))) { throw new XFormsException( "ModelSubmissionHandler only supports 'none' or 'instance' as replace mode"); } String submissionMethod = submission.getMethod(); String resourceAttr = getURI(); String resourceModelId = null; String instanceId = null; String xpath = null; try { int devider = resourceAttr.indexOf("#"); resourceModelId = resourceAttr.substring(resourceAttr.indexOf(":") + 1, devider); int instanceIdStart = resourceAttr.indexOf("(") + 1; int instanceIdEnd = resourceAttr.indexOf(")"); instanceId = resourceAttr.substring(instanceIdStart + 1, instanceIdEnd - 1); if (resourceAttr.indexOf("/") != -1) { xpath = resourceAttr.substring(resourceAttr.indexOf("/")); } else { throw new XFormsException( "Syntax error: xpath mustn't be null. You've to provide at least the path to the rootnode."); } } catch (IndexOutOfBoundsException e) { throw new XFormsException("Syntax error in expression: " + resourceAttr); } Model providerModel; Model receiverModel; if (submissionMethod.equalsIgnoreCase("get")) { providerModel = submission.getContainerObject().getModel(resourceModelId); receiverModel = submission.getModel(); Node targetNode = XPathUtil.getAsNode(XPathCache.getInstance().evaluate( providerModel.getInstance(instanceId).getRootContext().getNodeset(), 1, xpath, providerModel.getPrefixMapping(), providerModel.getXPathFunctionContext()), 1); if (targetNode == null) { throw new XFormsException("targetNode for xpath: " + xpath + " not found"); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("targetNode to replace............"); DOMUtil.prettyPrintDOM(targetNode); } Document result = DOMUtil.newDocument(true, false); result.appendChild(result.importNode(targetNode.cloneNode(true), true)); if (LOGGER.isDebugEnabled()) { LOGGER.debug("result Instance after insertion ............"); DOMUtil.prettyPrintDOM(result); } Map response = new HashMap(1); response.put(XFormsProcessor.SUBMISSION_RESPONSE_DOCUMENT, result); return response; } else if (submissionMethod.equalsIgnoreCase("post")) { providerModel = submission.getModel(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Instance Data to post............"); DOMUtil.prettyPrintDOM(instance); } receiverModel = submission.getContainerObject().getModel(resourceModelId); Node targetNode = XPathUtil.getAsNode(XPathCache.getInstance().evaluate( receiverModel.getInstance(instanceId).getRootContext().getNodeset(), 1, xpath, receiverModel.getPrefixMapping(), receiverModel.getXPathFunctionContext()), 1); if (targetNode == null) { throw new XFormsException("targetNode for xpath: " + xpath + " not found"); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("targetNode to replace............"); DOMUtil.prettyPrintDOM(targetNode); } //todo:review - this can be an Eleement if ref was used on submission!!! if (instance instanceof Document) { Document toImport = (Document) instance; targetNode.getParentNode().replaceChild( targetNode.getOwnerDocument().importNode(toImport.getDocumentElement(), true), targetNode); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("result Instance after insertion ............"); DOMUtil.prettyPrintDOM(receiverModel.getDefaultInstance().getInstanceDocument()); } } else { throw new XFormsException("Submission method '" + submissionMethod + "' not supported"); } receiverModel.rebuild(); receiverModel.recalculate(); receiverModel.revalidate(); receiverModel.refresh(); return new HashMap(1); } catch (Exception e) { throw new XFormsException(e); } }
From source file:org.talend.mdm.webapp.browserecords.server.actions.BrowseRecordsAction.java
private Object[] getItemBeans(String dataClusterPK, ViewBean viewBean, EntityModel entityModel, String criteria, int skip, int max, String sortDir, String sortCol, String language) throws Exception { int totalSize = 0; String dateFormat = "yyyy-MM-dd"; //$NON-NLS-1$ String dateTimeFormat = "yyyy-MM-dd'T'HH:mm:ss"; //$NON-NLS-1$ List<ItemBean> itemBeans = new ArrayList<ItemBean>(); String concept = ViewHelper.getConceptFromDefaultViewName(viewBean.getViewPK()); Map<String, String[]> formatMap = this.checkDisplayFormat(entityModel, language); WSWhereItem wi = null;/*from w w w . j a v a 2 s .c om*/ if (criteria != null) { wi = CommonUtil.buildWhereItems(criteria); } String[] results = CommonUtil.getPort().viewSearch(new WSViewSearch(new WSDataClusterPK(dataClusterPK), new WSViewPK(viewBean.getViewPK()), wi, -1, skip, max, sortCol, sortDir)).getStrings(); // set foreignKey's EntityModel Map<String, EntityModel> map = new HashMap<String, EntityModel>(); if (results.length > 0 && viewBean.getViewableXpaths() != null) { for (String xpath : viewBean.getViewableXpaths()) { TypeModel typeModel = entityModel.getMetaDataTypes().get(xpath); if (typeModel != null && typeModel.getForeignkey() != null) { map.put(xpath, getEntityModel(typeModel.getForeignkey().split("/")[0], language)); //$NON-NLS-1$ } } } // TODO change ids to array? List<String> idsArray = new ArrayList<String>(); for (int i = 0; i < results.length; i++) { if (i == 0) { try { // Qizx doesn't wrap the count in a XML element, so try to parse it totalSize = Integer.parseInt(results[i]); } catch (NumberFormatException e) { totalSize = Integer.parseInt(com.amalto.webapp.core.util.Util.parse(results[i]) .getDocumentElement().getTextContent()); } continue; } Document doc = parseResultDocument(results[i], "result"); //$NON-NLS-1$ idsArray.clear(); for (String key : entityModel.getKeys()) { String id = com.amalto.core.util.Util.getFirstTextNode(doc.getDocumentElement(), "." + key.substring(key.lastIndexOf('/'))); //$NON-NLS-1$ if (id != null) { idsArray.add(id); } } Set<String> keySet = formatMap.keySet(); Map<String, Object> originalMap = new HashMap<String, Object>(); Map<String, String> formateValueMap = new HashMap<String, String>(); for (String key : keySet) { String[] value = formatMap.get(key); TypeModel tm = entityModel.getMetaDataTypes().get(key); String xpath = tm.getXpath(); String dataText = null; if (!key.equals(xpath)) { NodeList list = com.amalto.core.util.Util.getNodeList(doc.getDocumentElement(), xpath.replaceFirst(concept + "/", "./")); //$NON-NLS-1$//$NON-NLS-2$ if (list != null) { for (int k = 0; k < list.getLength(); k++) { Node node = list.item(k); String realType = ((Element) node.getParentNode()).getAttribute("xsi:type"); //$NON-NLS-1$ if (key.replaceAll(":" + realType, "").equals(xpath)) { //$NON-NLS-1$//$NON-NLS-2$ dataText = node.getTextContent(); break; } } } } else { dataText = com.amalto.core.util.Util.getFirstTextNode(doc.getDocumentElement(), key.replaceFirst(concept + "/", "./")); //$NON-NLS-1$ //$NON-NLS-2$ } if (dataText != null) { if (dataText.trim().length() != 0) { if (dateTypeNames.contains(tm.getType().getBaseTypeName())) { SimpleDateFormat sdf = null; if (value[1].equalsIgnoreCase("DATE")) { //$NON-NLS-1$ sdf = new SimpleDateFormat(dateFormat, java.util.Locale.ENGLISH); } else if (value[1].equalsIgnoreCase("DATETIME")) { //$NON-NLS-1$ sdf = new SimpleDateFormat(dateTimeFormat, java.util.Locale.ENGLISH); } try { Date date = sdf.parse(dataText.trim()); originalMap.put(key, date); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); String formatValue = com.amalto.webapp.core.util.Util.formatDate(value[0], calendar); formateValueMap.put(key, formatValue); com.amalto.core.util.Util .getNodeList(doc.getDocumentElement(), key.replaceFirst(concept + "/", "./")) //$NON-NLS-1$//$NON-NLS-2$ .item(0).setTextContent(formatValue); } catch (Exception e) { originalMap.remove(key); formateValueMap.remove(key); } } else if (numberTypeNames.contains(tm.getType().getBaseTypeName())) { try { NumberFormat nf = NumberFormat.getInstance(); Number num = nf.parse(dataText.trim()); String formatValue = ""; //$NON-NLS-1$ if (tm.getType().getBaseTypeName() .equals(DataTypeConstants.DOUBLE.getBaseTypeName())) { formatValue = String.format(value[0], num.doubleValue()).trim(); } else if (tm.getType().getBaseTypeName() .equals(DataTypeConstants.FLOAT.getBaseTypeName())) { formatValue = String.format(value[0], num.floatValue()).trim(); } else if (tm.getType().getBaseTypeName() .equals(DataTypeConstants.DECIMAL.getBaseTypeName())) { formatValue = String.format(value[0], new BigDecimal(dataText.trim())).trim(); } else { formatValue = String.format(value[0], num).trim(); } originalMap.put(key, num); formateValueMap.put(key, formatValue); com.amalto.core.util.Util .getNodeList(doc.getDocumentElement(), key.replaceFirst(concept + "/", "./")) //$NON-NLS-1$//$NON-NLS-2$ .item(0).setTextContent(formatValue); } catch (Exception e) { Log.info("format has error 111"); //$NON-NLS-1$ originalMap.remove(key); formateValueMap.remove(key); } } } } } ItemBean itemBean = new ItemBean(concept, CommonUtil.joinStrings(idsArray, "."), //$NON-NLS-1$ XMLUtils.nodeToString(doc.getDocumentElement(), true, true)); itemBean.setOriginalMap(originalMap); itemBean.setFormateMap(formateValueMap); if (checkSmartViewExistsByLang(concept, language)) { itemBean.setSmartViewMode(ItemBean.SMARTMODE); } else if (checkSmartViewExistsByOpt(concept, language)) { itemBean.setSmartViewMode(ItemBean.PERSOMODE); } dynamicAssembleByResultOrder(itemBean, viewBean, entityModel, map, language); itemBeans.add(itemBean); } return new Object[] { itemBeans, totalSize }; }
From source file:com.rapid.server.Designer.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { RapidRequest rapidRequest = new RapidRequest(this, request); try {// w w w . j a v a2s . c o m String output = ""; // read bytes from request body into our own byte array (this means we can deal with images) InputStream input = request.getInputStream(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); for (int length = 0; (length = input.read(_byteBuffer)) > -1;) outputStream.write(_byteBuffer, 0, length); byte[] bodyBytes = outputStream.toByteArray(); // get the rapid application Application rapidApplication = getApplications().get("rapid"); // check we got one if (rapidApplication != null) { // get rapid security SecurityAdapter rapidSecurity = rapidApplication.getSecurityAdapter(); // check we got some if (rapidSecurity != null) { // get user name String userName = rapidRequest.getUserName(); if (userName == null) userName = ""; // check permission if (rapidSecurity.checkUserRole(rapidRequest, Rapid.DESIGN_ROLE)) { Application application = rapidRequest.getApplication(); if (application != null) { if ("savePage".equals(rapidRequest.getActionName())) { String bodyString = new String(bodyBytes, "UTF-8"); getLogger().debug("Designer POST request : " + request.getQueryString() + " body : " + bodyString); JSONObject jsonPage = new JSONObject(bodyString); // instantiate a new blank page Page newPage = new Page(); // set page properties newPage.setId(jsonPage.optString("id")); newPage.setName(jsonPage.optString("name")); newPage.setTitle(jsonPage.optString("title")); newPage.setFormPageType(jsonPage.optInt("formPageType")); newPage.setLabel(jsonPage.optString("label")); newPage.setDescription(jsonPage.optString("description")); newPage.setSimple(jsonPage.optBoolean("simple")); // look in the JSON for an event array JSONArray jsonEvents = jsonPage.optJSONArray("events"); // add the events if we found one if (jsonEvents != null) newPage.setEvents(Control.getEvents(this, jsonEvents)); // look in the JSON for a styles array JSONArray jsonStyles = jsonPage.optJSONArray("styles"); // if there were styles if (jsonStyles != null) newPage.setStyles(Control.getStyles(this, jsonStyles)); // if there are child controls from the page loop them and add to the pages control collection JSONArray jsonControls = jsonPage.optJSONArray("childControls"); if (jsonControls != null) { for (int i = 0; i < jsonControls.length(); i++) { // get the JSON control JSONObject jsonControl = jsonControls.getJSONObject(i); // call our function so it can go iterative newPage.addControl(createControl(jsonControl)); } } // if there are roles specified for this page JSONArray jsonUserRoles = jsonPage.optJSONArray("roles"); if (jsonUserRoles != null) { List<String> userRoles = new ArrayList<String>(); for (int i = 0; i < jsonUserRoles.length(); i++) { // get the JSON role String jsonUserRole = jsonUserRoles.getString(i); // add to collection userRoles.add(jsonUserRole); } // assign to page newPage.setRoles(userRoles); } // look in the JSON for a sessionVariables array JSONArray jsonSessionVariables = jsonPage.optJSONArray("sessionVariables"); // if we found one if (jsonSessionVariables != null) { List<String> sessionVariables = new ArrayList<String>(); for (int i = 0; i < jsonSessionVariables.length(); i++) { sessionVariables.add(jsonSessionVariables.getString(i)); } newPage.setSessionVariables(sessionVariables); } // look in the JSON for a pageVisibilityRules array JSONArray jsonVisibilityConditions = jsonPage.optJSONArray("visibilityConditions"); // if we found one if (jsonVisibilityConditions != null) { List<Condition> visibilityConditions = new ArrayList<Condition>(); for (int i = 0; i < jsonVisibilityConditions.length(); i++) { visibilityConditions .add(new Condition(jsonVisibilityConditions.getJSONObject(i))); } newPage.setVisibilityConditions(visibilityConditions); } // look in the JSON for a pageVisibilityRules array is an and or or (default to and) String jsonConditionsType = jsonPage.optString("conditionsType", "and"); // set what we got newPage.setConditionsType(jsonConditionsType); // retrieve the html body String htmlBody = jsonPage.optString("htmlBody"); // if we got one trim it and retain in page if (htmlBody != null) newPage.setHtmlBody(htmlBody.trim()); // look in the JSON for rolehtml JSONArray jsonRolesHtml = jsonPage.optJSONArray("rolesHtml"); // if we found some if (jsonRolesHtml != null) { // instantiate the roles html collection ArrayList<Page.RoleHtml> rolesHtml = new ArrayList<Page.RoleHtml>(); // loop the entries for (int i = 0; i < jsonRolesHtml.length(); i++) { // get the entry JSONObject jsonRoleHtml = jsonRolesHtml.getJSONObject(i); // retain the html String html = jsonRoleHtml.optString("html"); // trim it if there is one if (html != null) html = html.trim(); // create an array to hold the roles ArrayList<String> roles = new ArrayList<String>(); // get the roles JSONArray jsonRoles = jsonRoleHtml.optJSONArray("roles"); // if we got some if (jsonRoles != null) { // loop them for (int j = 0; j < jsonRoles.length(); j++) { // get the role String role = jsonRoles.getString(j); // add it to the roles collections roles.add(role); } } // create and add a new roleHtml object rolesHtml.add(new Page.RoleHtml(roles, html)); } // add it to the page newPage.setRolesHtml(rolesHtml); } // fetch a copy of the old page (if there is one) Page oldPage = application.getPages().getPage(getServletContext(), newPage.getId()); // if the page's name changed we need to remove it if (oldPage != null) { if (!oldPage.getName().equals(newPage.getName())) { oldPage.delete(this, rapidRequest, application); } } // save the new page to file newPage.save(this, rapidRequest, application, true); // get any pages collection (we're only sent it if it's been changed) JSONArray jsonPages = jsonPage.optJSONArray("pages"); // if we got some if (jsonPages != null) { // make a new map for the page orders Map<String, Integer> pageOrders = new HashMap<String, Integer>(); // loop the page orders for (int i = 0; i < jsonPages.length(); i++) { // add the order to the map pageOrders.put(jsonPages.getJSONObject(i).getString("id"), i); } // replace the application pageOrders map application.setPageOrders(pageOrders); // save the application and the new orders application.save(this, rapidRequest, true); } boolean jsonPageOrderReset = jsonPage.optBoolean("pageOrderReset"); if (jsonPageOrderReset) { // empty the application pageOrders map so everything goes alphabetical application.setPageOrders(null); } // send a positive message output = "{\"message\":\"Saved!\"}"; // set the response type to json response.setContentType("application/json"); } else if ("testSQL".equals(rapidRequest.getActionName())) { // turn the body bytes into a string String bodyString = new String(bodyBytes, "UTF-8"); JSONObject jsonQuery = new JSONObject(bodyString); JSONArray jsonInputs = jsonQuery.optJSONArray("inputs"); JSONArray jsonOutputs = jsonQuery.optJSONArray("outputs"); Parameters parameters = new Parameters(); if (jsonInputs != null) { for (int i = 0; i < jsonInputs.length(); i++) parameters.addNull(); } DatabaseConnection databaseConnection = application.getDatabaseConnections() .get(jsonQuery.optInt("databaseConnectionIndex", 0)); ConnectionAdapter ca = databaseConnection.getConnectionAdapter(getServletContext(), application); DataFactory df = new DataFactory(ca); int outputs = 0; if (jsonOutputs != null) outputs = jsonOutputs.length(); String sql = jsonQuery.getString("SQL"); // some jdbc drivers need the line breaks removing before they'll work properly - here's looking at you MS SQL Server! sql = sql.replace("\n", " "); if (outputs == 0) { df.getPreparedStatement(rapidRequest, sql, parameters); } else { ResultSet rs = df.getPreparedResultSet(rapidRequest, sql, parameters); ResultSetMetaData rsmd = rs.getMetaData(); int cols = rsmd.getColumnCount(); if (outputs > cols) throw new Exception(outputs + " outputs, but only " + cols + " column" + (cols > 1 ? "s" : "") + " selected"); for (int i = 0; i < outputs; i++) { JSONObject jsonOutput = jsonOutputs.getJSONObject(i); String field = jsonOutput.optString("field", ""); if (!"".equals(field)) { field = field.toLowerCase(); boolean gotOutput = false; for (int j = 0; j < cols; j++) { String sqlField = rsmd.getColumnLabel(j + 1).toLowerCase(); if (field.equals(sqlField)) { gotOutput = true; break; } } if (!gotOutput) { rs.close(); df.close(); throw new Exception("Field \"" + field + "\" from output " + (i + 1) + " is not present in selected columns"); } } } // close the recordset rs.close(); // close the data factory df.close(); } // send a positive message output = "{\"message\":\"OK\"}"; // set the response type to json response.setContentType("application/json"); } else if ("uploadImage".equals(rapidRequest.getActionName()) || "import".equals(rapidRequest.getActionName())) { // get the content type from the request String contentType = request.getContentType(); // get the position of the boundary from the content type int boundaryPosition = contentType.indexOf("boundary="); // derive the start of the meaning data by finding the boundary String boundary = contentType.substring(boundaryPosition + 10); // this is the double line break after which the data occurs byte[] pattern = { 0x0D, 0x0A, 0x0D, 0x0A }; // find the position of the double line break int dataPosition = Bytes.findPattern(bodyBytes, pattern); // the body header is everything up to the data String header = new String(bodyBytes, 0, dataPosition, "UTF-8"); // find the position of the filename in the data header int filenamePosition = header.indexOf("filename=\""); // extract the file name String filename = header.substring(filenamePosition + 10, header.indexOf("\"", filenamePosition + 10)); // find the position of the file type in the data header int fileTypePosition = header.toLowerCase().indexOf("type:"); // extract the file type String fileType = header.substring(fileTypePosition + 6); if ("uploadImage".equals(rapidRequest.getActionName())) { // check the file type if (!fileType.equals("image/jpeg") && !fileType.equals("image/gif") && !fileType.equals("image/png")) throw new Exception("Unsupported file type"); // get the web folder from the application String path = rapidRequest.getApplication().getWebFolder(getServletContext()); // create a file output stream to save the data to FileOutputStream fos = new FileOutputStream(path + "/" + filename); // write the file data to the stream fos.write(bodyBytes, dataPosition + pattern.length, bodyBytes.length - dataPosition - pattern.length - boundary.length() - 9); // close the stream fos.close(); // log the file creation getLogger().debug("Saved image file " + path + filename); // create the response with the file name and upload type output = "{\"file\":\"" + filename + "\",\"type\":\"" + rapidRequest.getActionName() + "\"}"; } else if ("import".equals(rapidRequest.getActionName())) { // check the file type if (!"application/x-zip-compressed".equals(fileType) && !"application/zip".equals(fileType)) throw new Exception("Unsupported file type"); // get the name String appName = request.getParameter("name"); // check we were given one if (appName == null) throw new Exception("Name must be provided"); // get the version String appVersion = request.getParameter("version"); // check we were given one if (appVersion == null) throw new Exception("Version must be provided"); // make the id from the safe and lower case name String appId = Files.safeName(appName).toLowerCase(); // make the version from the safe and lower case name appVersion = Files.safeName(appVersion); // get application destination folder File appFolderDest = new File( Application.getConfigFolder(getServletContext(), appId, appVersion)); // get web contents destination folder File webFolderDest = new File( Application.getWebFolder(getServletContext(), appId, appVersion)); // look for an existing application of this name and version Application existingApplication = getApplications().get(appId, appVersion); // if we have an existing application if (existingApplication != null) { // back it up first existingApplication.backup(this, rapidRequest, false); } // get a file for the temp directory File tempDir = new File(getServletContext().getRealPath("/WEB-INF/temp")); // create it if not there if (!tempDir.exists()) tempDir.mkdir(); // the path we're saving to is the temp folder String path = getServletContext() .getRealPath("/WEB-INF/temp/" + appId + ".zip"); // create a file output stream to save the data to FileOutputStream fos = new FileOutputStream(path); // write the file data to the stream fos.write(bodyBytes, dataPosition + pattern.length, bodyBytes.length - dataPosition - pattern.length - boundary.length() - 9); // close the stream fos.close(); // log the file creation getLogger().debug("Saved import file " + path); // get a file object for the zip file File zipFile = new File(path); // load it into a zip file object ZipFile zip = new ZipFile(zipFile); // unzip the file zip.unZip(); // delete the zip file zipFile.delete(); // unzip folder (for deletion) File unZipFolder = new File( getServletContext().getRealPath("/WEB-INF/temp/" + appId)); // get application folders File appFolderSource = new File( getServletContext().getRealPath("/WEB-INF/temp/" + appId + "/WEB-INF")); // get web content folders File webFolderSource = new File(getServletContext() .getRealPath("/WEB-INF/temp/" + appId + "/WebContent")); // check we have the right source folders if (webFolderSource.exists() && appFolderSource.exists()) { // get application.xml file File appFileSource = new File(appFolderSource + "/application.xml"); if (appFileSource.exists()) { // delete the appFolder if it exists if (appFolderDest.exists()) Files.deleteRecurring(appFolderDest); // delete the webFolder if it exists if (webFolderDest.exists()) Files.deleteRecurring(webFolderDest); // copy application content Files.copyFolder(appFolderSource, appFolderDest); // copy web content Files.copyFolder(webFolderSource, webFolderDest); try { // load the new application (but don't initialise, nor load pages) Application appNew = Application.load(getServletContext(), new File(appFolderDest + "/application.xml"), false); // update application name appNew.setName(appName); // get the old id String appOldId = appNew.getId(); // make the new id appId = Files.safeName(appName).toLowerCase(); // update the id appNew.setId(appId); // get the old version String appOldVersion = appNew.getVersion(); // make the new version appVersion = Files.safeName(appVersion); // update the version appNew.setVersion(appVersion); // update the created date appNew.setCreatedDate(new Date()); // set the status to In development appNew.setStatus(Application.STATUS_DEVELOPMENT); // a map of actions that might be removed from any of the pages Map<String, Integer> removedActions = new HashMap<String, Integer>(); // look for page files File pagesFolder = new File( appFolderDest.getAbsolutePath() + "/pages"); // if the folder is there if (pagesFolder.exists()) { // create a filter for finding .page.xml files FilenameFilter xmlFilenameFilter = new FilenameFilter() { public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".page.xml"); } }; // loop the .page.xml files for (File pageFile : pagesFolder.listFiles(xmlFilenameFilter)) { BufferedReader reader = new BufferedReader( new InputStreamReader(new FileInputStream(pageFile), "UTF-8")); String line = null; StringBuilder stringBuilder = new StringBuilder(); while ((line = reader.readLine()) != null) { stringBuilder.append(line); stringBuilder.append("\n"); } reader.close(); // retrieve the xml into a string String fileString = stringBuilder.toString(); // prepare a new file string which will update into String newFileString = null; // if the old app did not have a version (for backwards compatibility) if (appOldVersion == null) { // replace all properties that appear to have a url, and all created links - note the fix for cleaning up the double encoding newFileString = fileString .replace("applications/" + appOldId + "/", "applications/" + appId + "/" + appVersion + "/") .replace("~?a=" + appOldId + "&", "~?a=" + appId + "&v=" + appVersion + "&") .replace("~?a=" + appOldId + "&amp;", "~?a=" + appId + "&v=" + appVersion + "&"); } else { // replace all properties that appear to have a url, and all created links - note the fix for double encoding newFileString = fileString .replace( "applications/" + appOldId + "/" + appOldVersion + "/", "applications/" + appId + "/" + appVersion + "/") .replace( "~?a=" + appOldId + "&v=" + appOldVersion + "&", "~?a=" + appId + "&v=" + appVersion + "&") .replace( "~?a=" + appOldId + "&amp;v=" + appOldVersion + "&amp;", "~?a=" + appId + "&v=" + appVersion + "&"); } // now open the string into a document Document pageDocument = XML.openDocument(newFileString); // get an xpath factory XPathFactory xPathfactory = XPathFactory.newInstance(); XPath xpath = xPathfactory.newXPath(); // an expression for any attributes with a local name of "type" XPathExpression expr = xpath .compile("//@*[local-name()='type']"); // get them NodeList nl = (NodeList) expr.evaluate(pageDocument, XPathConstants.NODESET); // get out system actions JSONArray jsonActions = getJsonActions(); // if we found any elements with a type attribute and we have system actions if (nl.getLength() > 0 && jsonActions.length() > 0) { // a list of action types List<String> types = new ArrayList<String>(); // loop the json actions for (int i = 0; i < jsonActions.length(); i++) types.add(jsonActions.getJSONObject(i) .optString("type").toLowerCase()); // loop the action attributes we found for (int i = 0; i < nl.getLength(); i++) { // get this attribute Attr a = (Attr) nl.item(i); // get the value of the type String type = a.getTextContent().toLowerCase(); // get the element the attribute is in Node n = a.getOwnerElement(); // if we don't know about this action type if (!types.contains(type)) { // get the parent node Node p = n.getParentNode(); // remove this node p.removeChild(n); // if we have removed this type already if (removedActions.containsKey(type)) { // increment the entry for this type removedActions.put(type, removedActions.get(type) + 1); } else { // add an entry for this type removedActions.put(type, 1); } } // got type check } // attribute loop } // attribute and system action check // use the transformer to write to disk TransformerFactory transformerFactory = TransformerFactory .newInstance(); Transformer transformer = transformerFactory .newTransformer(); DOMSource source = new DOMSource(pageDocument); StreamResult result = new StreamResult(pageFile); transformer.transform(source, result); } // page xml file loop } // pages folder check // now initialise with the new id but don't make the resource files (this reloads the pages and sets up the security adapter) appNew.initialise(getServletContext(), false); // get the security for this application SecurityAdapter security = appNew.getSecurityAdapter(); // if we have one if (security != null) { // assume we don't have the user boolean gotUser = false; // get the current users record from the adapter User user = security.getUser(rapidRequest); // check the current user is present in the app's security adapter if (user != null) { // now check the current user password is correct too if (security.checkUserPassword(rapidRequest, userName, rapidRequest.getUserPassword())) { // we have the right user with the right password gotUser = true; } else { // remove this user as the password does not match security.deleteUser(rapidRequest); } } // if we don't have the user if (!gotUser) { // get the current user from the Rapid application User rapidUser = rapidSecurity.getUser(rapidRequest); // create a new user based on the Rapid user user = new User(userName, rapidUser.getDescription(), rapidUser.getPassword()); // add the new user security.addUser(rapidRequest, user); } // add Admin and Design roles for the new user if required if (!security.checkUserRole(rapidRequest, com.rapid.server.Rapid.ADMIN_ROLE)) security.addUserRole(rapidRequest, com.rapid.server.Rapid.ADMIN_ROLE); if (!security.checkUserRole(rapidRequest, com.rapid.server.Rapid.DESIGN_ROLE)) security.addUserRole(rapidRequest, com.rapid.server.Rapid.DESIGN_ROLE); } // if any items were removed if (removedActions.keySet().size() > 0) { // a description of what was removed String removed = ""; // loop the entries for (String type : removedActions.keySet()) { int count = removedActions.get(type); removed += "removed " + count + " " + type + " action" + (count == 1 ? "" : "s") + " on import\n"; } // get the current description String description = appNew.getDescription(); // if null set to empty string if (description == null) description = ""; // add a line break if need be if (description.length() > 0) description += "\n"; // add the removed description += removed; // set it back appNew.setDescription(description); } // reload the pages (actually clears down the pages collection and reloads the headers) appNew.getPages().loadpages(getServletContext()); // save application (this will also initialise and rebuild the resources) appNew.save(this, rapidRequest, false); // add application to the collection getApplications().put(appNew); // delete unzip folder Files.deleteRecurring(unZipFolder); // send a positive message output = "{\"id\":\"" + appNew.getId() + "\",\"version\":\"" + appNew.getVersion() + "\"}"; } catch (Exception ex) { // delete the appFolder if it exists if (appFolderDest.exists()) Files.deleteRecurring(appFolderDest); // if the parent is empty delete it too if (appFolderDest.getParentFile().list().length <= 1) Files.deleteRecurring(appFolderDest.getParentFile()); // delete the webFolder if it exists if (webFolderDest.exists()) Files.deleteRecurring(webFolderDest); // if the parent is empty delete it too if (webFolderDest.getParentFile().list().length <= 1) Files.deleteRecurring(webFolderDest.getParentFile()); // rethrow exception throw ex; } } else { // delete unzip folder Files.deleteRecurring(unZipFolder); // throw excpetion throw new Exception("Must be a valid Rapid " + Rapid.VERSION + " file"); } } else { // delete unzip folder Files.deleteRecurring(unZipFolder); // throw excpetion throw new Exception("Must be a valid Rapid file"); } } } getLogger().debug("Designer POST response : " + output); PrintWriter out = response.getWriter(); out.print(output); out.close(); } // got an application } // got rapid design role } // got rapid security } // got rapid application } catch (Exception ex) { getLogger().error("Designer POST error : ", ex); sendException(rapidRequest, response, ex); } }
From source file:com.nortal.jroad.typegen.xmlbeans.XteeSchemaCodePrinter.java
private String findXteeTitle(SchemaProperty prop) throws IOException { String xteeTitle = null;/*from w w w . ja v a 2s . co m*/ try { String localPart = prop.getName().getLocalPart(); Node propNode = ((SchemaTypeImpl) prop.getContainerType()).getParseObject().getDomNode(); Node node = propNode; if (StringUtils.equals(localPart, "item") || StringUtils.equals(localPart, "all")) { while (true) { if (StringUtils.equals(node.getLocalName(), "element")) { localPart = node.getAttributes().getNamedItem("name").getNodeValue(); break; } node = node.getParentNode(); if (node == null) { node = findFirstNode(propNode.getChildNodes(), "element", localPart); break; } } } else { node = findFirstNode(node.getChildNodes(), "element", localPart); } if (node != null) { xteeTitle = clearString( getXmlObjectValue(findFirstNode(node.getChildNodes(), "title", null, false))); if (xteeTitle == null) { xteeTitle = StringUtils.capitalize(node.getAttributes().getNamedItem("name").getNodeValue()); } } } catch (Exception e) { throw new IOException(e); } return xteeTitle; }