List of usage examples for org.w3c.dom Node removeChild
public Node removeChild(Node oldChild) throws DOMException;
oldChild
from the list of children, and returns it. From source file:gov.nih.nci.ncicb.tcga.dcc.qclive.common.action.ClinicalDateObscurer.java
/** * This method removes a child from its parent (how horrible) and any preceding newlines and whitespace * * @param parent the Node holdind the child to be removed * @param child the Node to be removed// ww w . j a v a2 s.co m */ private void removeChildNode(final Node parent, final Node child) { Node childPreviousSibling = child.getPreviousSibling(); if (childPreviousSibling != null && childPreviousSibling.getNodeType() == Node.TEXT_NODE && childPreviousSibling.getTextContent().trim().equals("")) { //We want to remove newlines (and whitespace) preceding the child to be removed //so has to avoid blank lines in the XML after the child is removed parent.removeChild(childPreviousSibling); } //Remove child parent.removeChild(child); }
From source file:com.cloud.hypervisor.kvm.resource.wrapper.LibvirtMigrateCommandWrapper.java
private String replaceStorage(String xmlDesc, Map<String, MigrateCommand.MigrateDiskInfo> migrateStorage) throws IOException, ParserConfigurationException, SAXException, TransformerException { InputStream in = IOUtils.toInputStream(xmlDesc); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document doc = docBuilder.parse(in); // Get the root element Node domainNode = doc.getFirstChild(); NodeList domainChildNodes = domainNode.getChildNodes(); for (int i = 0; i < domainChildNodes.getLength(); i++) { Node domainChildNode = domainChildNodes.item(i); if ("devices".equals(domainChildNode.getNodeName())) { NodeList devicesChildNodes = domainChildNode.getChildNodes(); for (int x = 0; x < devicesChildNodes.getLength(); x++) { Node deviceChildNode = devicesChildNodes.item(x); if ("disk".equals(deviceChildNode.getNodeName())) { Node diskNode = deviceChildNode; String sourceFileDevText = getSourceFileDevText(diskNode); String path = getPathFromSourceFileDevText(migrateStorage.keySet(), sourceFileDevText); if (path != null) { MigrateCommand.MigrateDiskInfo migrateDiskInfo = migrateStorage.remove(path); NamedNodeMap diskNodeAttributes = diskNode.getAttributes(); Node diskNodeAttribute = diskNodeAttributes.getNamedItem("type"); diskNodeAttribute.setTextContent(migrateDiskInfo.getDiskType().toString()); NodeList diskChildNodes = diskNode.getChildNodes(); for (int z = 0; z < diskChildNodes.getLength(); z++) { Node diskChildNode = diskChildNodes.item(z); if ("driver".equals(diskChildNode.getNodeName())) { Node driverNode = diskChildNode; NamedNodeMap driverNodeAttributes = driverNode.getAttributes(); Node driverNodeAttribute = driverNodeAttributes.getNamedItem("type"); driverNodeAttribute.setTextContent(migrateDiskInfo.getDriverType().toString()); } else if ("source".equals(diskChildNode.getNodeName())) { diskNode.removeChild(diskChildNode); Element newChildSourceNode = doc.createElement("source"); newChildSourceNode.setAttribute(migrateDiskInfo.getSource().toString(), migrateDiskInfo.getSourceText()); diskNode.appendChild(newChildSourceNode); } else if ("auth".equals(diskChildNode.getNodeName())) { diskNode.removeChild(diskChildNode); } else if ("iotune".equals(diskChildNode.getNodeName())) { diskNode.removeChild(diskChildNode); }/*w w w .j a v a2 s .c o m*/ } } } } } } if (!migrateStorage.isEmpty()) { throw new CloudRuntimeException( "Disk info was passed into LibvirtMigrateCommandWrapper.replaceStorage that was not used."); } return getXml(doc); }
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 ww.j a v a 2s. 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:edu.uams.clara.webapp.xml.processor.impl.DefaultXmlProcessorImpl.java
/** * replace elements in originalDom with modifiedDom according to listed * xPaths, if the originalDom has elements not listed in the xPath, it will * be kept untouched. in the HashMap<String, String> xPathPairs, the key is * the path in the source xml, and the value is the xpath for the final * note*: the if the xpath has attributes, it's not going to work... need to * do a custom implementation when that use case happened... * /*from w w w . j a v a 2s .com*/ * @param originalDom * @param modifiedDom * @param xPaths * @return * @throws XPathExpressionException */ private Document replaceByXPaths(final Document originalDom, final Document modifiedDom, Map<String, String> xPathPairs) throws XPathExpressionException { Document finalDom = originalDom; Element finalDomRoot = (Element) finalDom.getFirstChild(); Element lastChild = null; 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)); int el = existingNodeList.getLength(); logger.debug("find '" + el + "' in originalDom using xPath: " + destXPath); for (int i = 0; i < el; i++) { Node c = existingNodeList.item(i); // remove this node from its parent... c.getParentNode().removeChild(c); } // 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); xPath.reset(); // find all the nodes specified by srcXPath in the modifiedDom NodeList nodeList = (NodeList) (xPath.evaluate(srcXPath, modifiedDom, XPathConstants.NODESET)); int l = nodeList.getLength(); logger.debug("find '" + l + "' in modifiedXml using xPath: " + srcXPath); 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: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 ww w. j av a 2s . c o m 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:XMLConfig.java
/** Create the node specified by the DOM path. * @param path DOM path//from w w w . j a v a 2 s . c o m * @param n node where the search should start, or null for the root * @param overwrite whether to overwrite (true) or add (false) -- only applies for last node! * @return the node that was created, or the parent node of the attribute if it was an attribute */ public Node createNode(String path, Node n, boolean overwrite) { if (isDelegated()) { return _parent.createNode(path, n, overwrite); } if (n == null) { n = _document; } while (path.indexOf('/') > -1) { Node child = null; String nodeName = path.substring(0, path.indexOf('/')); path = path.substring(path.indexOf('/') + 1); child = n.getFirstChild(); while (child != null) { if (child.getNodeName().equals(nodeName)) { // found n = child; break; } child = child.getNextSibling(); } if (child == null) { // not found child = _document.createElement(nodeName); n.appendChild(child); n = child; } } String nodeName; if (path.indexOf('.') > -1) { nodeName = path.substring(0, path.indexOf('.')); } else { if (path.length() == 0) { throw new XMLConfigException("Cannot set node with empty name"); } nodeName = path; } Node child = null; if (nodeName.length() > 0) { if (overwrite) { child = n.getFirstChild(); while (child != null) { if (child.getNodeName().equals(nodeName)) { // found n = child; break; } child = child.getNextSibling(); } if (child == null) { child = _document.createElement(nodeName); n.appendChild(child); n = child; } } else { child = _document.createElement(nodeName); n.appendChild(child); n = child; } } if (path.indexOf('.') > -1) { if (!(n instanceof Element)) { throw new XMLConfigException( "Node " + n.getNodeName() + " should be an element so it can contain attributes"); } return n; } else { if (overwrite) { child = n.getFirstChild(); // remove all children while (child != null) { Node temp = child.getNextSibling(); n.removeChild(child); child = temp; } return n; } else { return child; } } }
From source file:de.betterform.xml.xforms.model.submission.Submission.java
/** * Performs replace processing according to section 11.1, para 5. *//*from w w w.ja v a2 s . co m*/ protected void submitReplaceText(Map response) throws XFormsException { if (getLogger().isDebugEnabled()) { getLogger().debug(this + " submit: replacing text"); } Node targetNode; if (this.targetExpr != null) { targetNode = XPathUtil .getAsNode( XPathCache.getInstance() .evaluate( this.instance == null ? evalInScopeContext() : this.model.getInstance(this.instance).getRootContext() .getNodeset(), 1, this.targetExpr, this.prefixMapping, this.xpathFunctionContext), 1); } else if (this.instance == null) { targetNode = this.model.getInstance(getInstanceId()).getInstanceDocument().getDocumentElement(); } else { targetNode = this.model.getInstance(this.instance).getInstanceDocument().getDocumentElement(); } final InputStream responseStream = (InputStream) response.get(XFormsProcessor.SUBMISSION_RESPONSE_STREAM); StringBuilder text = new StringBuilder(512); try { String contentType = (String) response.get("Content-Type"); String encoding = "UTF-8"; if (contentType != null) { final String[] contTypeEntries = contentType.split(", ?"); for (int i = 0; i < contTypeEntries.length; i++) { if (contTypeEntries[i].startsWith("charset=")) { encoding = contTypeEntries[i].substring(8); } } } byte[] buffer = new byte[512]; int bytesRead; while ((bytesRead = responseStream.read(buffer)) > 0) { text.append(new String(buffer, 0, bytesRead, encoding)); } responseStream.close(); } catch (Exception e) { // todo: check for response media type (needs submission response // refactoring) in order to dispatch xforms-link-exception throw new XFormsSubmitError("instance parsing failed", e, this.getTarget(), XFormsSubmitError.constructInfoObject(this.element, this.container, locationPath, XFormsConstants.PARSE_ERROR, getResourceURI(), 200d, null, "", "")); } if (targetNode == null) { throw new XFormsSubmitError("Invalid target", this.getTarget(), XFormsSubmitError.constructInfoObject(this.element, this.container, locationPath, XFormsConstants.TARGET_ERROR, getResourceURI(), 200d, null, "", "")); } else if (targetNode.getNodeType() == Node.ELEMENT_NODE) { while (targetNode.getFirstChild() != null) { targetNode.removeChild(targetNode.getFirstChild()); } targetNode.appendChild(targetNode.getOwnerDocument().createTextNode(text.toString())); } else if (targetNode.getNodeType() == Node.ATTRIBUTE_NODE) { targetNode.setNodeValue(text.toString()); } else { LOGGER.warn("Don't know how to handle targetNode '" + targetNode.getLocalName() + "', node is neither an element nor an attribute Node"); } // perform rebuild, recalculate, revalidate, and refresh this.model.rebuild(); this.model.recalculate(); this.model.revalidate(); this.container.refresh(); // deferred update behaviour UpdateHandler updateHandler = this.model.getUpdateHandler(); if (updateHandler != null) { updateHandler.doRebuild(false); updateHandler.doRecalculate(false); updateHandler.doRevalidate(false); updateHandler.doRefresh(false); } // dispatch xforms-submit-done this.container.dispatch(this.target, XFormsEventNames.SUBMIT_DONE, constructEventInfo(response)); }
From source file:lcmc.data.VMSXML.java
/** Add CPU match node. */ private void addCPUMatchNode(final Document doc, final Node root, final Map<String, String> parametersMap) { final String cpuMatch = parametersMap.get(VM_PARAM_CPU_MATCH); final Element cpuMatchNode = (Element) root.appendChild(doc.createElement("cpu")); if (!"".equals(cpuMatch)) { cpuMatchNode.setAttribute("match", cpuMatch); }// ww w . j a v a 2s .c o m final String model = parametersMap.get(VM_PARAM_CPUMATCH_MODEL); if (!"".equals(model)) { final Node modelNode = (Element) cpuMatchNode.appendChild(doc.createElement("model")); modelNode.appendChild(doc.createTextNode(model)); } final String vendor = parametersMap.get(VM_PARAM_CPUMATCH_VENDOR); if (!"".equals(vendor)) { final Node vendorNode = (Element) cpuMatchNode.appendChild(doc.createElement("vendor")); vendorNode.appendChild(doc.createTextNode(vendor)); } final String sockets = parametersMap.get(VM_PARAM_CPUMATCH_TOPOLOGY_SOCKETS); final String cores = parametersMap.get(VM_PARAM_CPUMATCH_TOPOLOGY_CORES); final String threads = parametersMap.get(VM_PARAM_CPUMATCH_TOPOLOGY_THREADS); final boolean isSockets = !"".equals(sockets); final boolean isCores = !"".equals(cores); final boolean isThreads = !"".equals(threads); if (isSockets || isCores || isThreads) { final Element topologyNode = (Element) cpuMatchNode.appendChild(doc.createElement("topology")); if (isSockets) { topologyNode.setAttribute("sockets", sockets); } if (isCores) { topologyNode.setAttribute("cores", cores); } if (isThreads) { topologyNode.setAttribute("threads", threads); } } final String policy = parametersMap.get(VM_PARAM_CPUMATCH_FEATURE_POLICY); final String features = parametersMap.get(VM_PARAM_CPUMATCH_FEATURES); if (!"".equals(policy) && !"".equals(features)) { for (final String feature : features.split("\\s+")) { final Element featureNode = (Element) cpuMatchNode.appendChild(doc.createElement("feature")); featureNode.setAttribute("policy", policy); featureNode.setAttribute("name", feature); } } if (!cpuMatchNode.hasChildNodes()) { root.removeChild(cpuMatchNode); } }
From source file:lcmc.data.VMSXML.java
/** Modify xml of the domain. */ public Node modifyDomainXML(final String domainName, final Map<String, String> parametersMap) { final String configName = namesConfigsMap.get(domainName); if (configName == null) { return null; }// ww w. j a va 2s .co m final Node domainNode = getDomainNode(domainName); if (domainNode == null) { return null; } final XPath xpath = XPathFactory.newInstance().newXPath(); final Map<String, String> paths = new HashMap<String, String>(); paths.put(VM_PARAM_MEMORY, "memory"); paths.put(VM_PARAM_CURRENTMEMORY, "currentMemory"); paths.put(VM_PARAM_VCPU, "vcpu"); paths.put(VM_PARAM_BOOTLOADER, "bootloader"); paths.put(VM_PARAM_BOOT, "os/boot"); paths.put(VM_PARAM_BOOT_2, "os/boot"); paths.put(VM_PARAM_TYPE, "os/type"); paths.put(VM_PARAM_TYPE_ARCH, "os/type"); paths.put(VM_PARAM_TYPE_MACHINE, "os/type"); paths.put(VM_PARAM_INIT, "os/init"); paths.put(VM_PARAM_LOADER, "os/loader"); paths.put(VM_PARAM_CPU_MATCH, "cpu"); paths.put(VM_PARAM_ACPI, "features"); paths.put(VM_PARAM_APIC, "features"); paths.put(VM_PARAM_PAE, "features"); paths.put(VM_PARAM_HAP, "features"); paths.put(VM_PARAM_ON_POWEROFF, "on_poweroff"); paths.put(VM_PARAM_ON_REBOOT, "on_reboot"); paths.put(VM_PARAM_ON_CRASH, "on_crash"); paths.put(VM_PARAM_EMULATOR, "devices/emulator"); final Document doc = domainNode.getOwnerDocument(); try { for (final String param : parametersMap.keySet()) { final String path = paths.get(param); if (path == null) { continue; } final NodeList nodes = (NodeList) xpath.evaluate(path, domainNode, XPathConstants.NODESET); Element node = (Element) nodes.item(0); if (node == null) { continue; } if (VM_PARAM_BOOT_2.equals(param)) { if (nodes.getLength() > 1) { node = (Element) nodes.item(1); } else { node = (Element) node.getParentNode().appendChild(doc.createElement(OS_BOOT_NODE)); } } String value = parametersMap.get(param); if (VM_PARAM_MEMORY.equals(param) || VM_PARAM_CURRENTMEMORY.equals(param)) { value = Long.toString(Tools.convertToKilobytes(value)); } if (VM_PARAM_CPU_MATCH.equals(param) || VM_PARAM_ACPI.equals(param) || VM_PARAM_APIC.equals(param) || VM_PARAM_PAE.equals(param) || VM_PARAM_HAP.equals(param)) { domainNode.removeChild(node); } else if (VM_PARAM_BOOT.equals(param)) { node.setAttribute(OS_BOOT_NODE_DEV, value); } else if (VM_PARAM_BOOT_2.equals(param)) { if (value == null || "".equals(value)) { node.getParentNode().removeChild(node); } else { node.setAttribute(OS_BOOT_NODE_DEV, value); } } else if (VM_PARAM_TYPE_ARCH.equals(param)) { node.setAttribute("arch", value); } else if (VM_PARAM_TYPE_MACHINE.equals(param)) { node.setAttribute("machine", value); } else if (VM_PARAM_CPU_MATCH.equals(param)) { if ("".equals(value)) { node.getParentNode().removeChild(node); } else { node.setAttribute("match", value); } } else if (VM_PARAM_CPUMATCH_TOPOLOGY_THREADS.equals(param)) { node.setAttribute("threads", value); } else { final Node n = getChildNode(node, "#text"); if (n == null) { node.appendChild(doc.createTextNode(value)); } else { n.setNodeValue(value); } } } addCPUMatchNode(doc, domainNode, parametersMap); addFeatures(doc, domainNode, parametersMap); } catch (final javax.xml.xpath.XPathExpressionException e) { Tools.appError("could not evaluate: ", e); return null; } return domainNode; }