List of usage examples for org.w3c.dom Attr getTextContent
public String getTextContent() throws DOMException;
From source file:edu.cornell.mannlib.semservices.service.impl.AgrovocService.java
protected List<String> getConceptURIsListFromRDF(String rdf) { List<String> conceptUris = new ArrayList<String>(); try {//from ww w. j a v a 2 s . c o m Document doc = XMLUtils.parse(rdf); NodeList nodes = doc.getElementsByTagName("skos:Concept"); int numberNodes = nodes.getLength(); int n; for (n = 0; n < numberNodes; n++) { Node node = nodes.item(n); NamedNodeMap attrs = node.getAttributes(); Attr idAttr = (Attr) attrs.getNamedItem("rdf:about"); String conceptUri = idAttr.getTextContent(); conceptUris.add(conceptUri); } } catch (IOException e) { e.printStackTrace(); System.err.println("rdf: " + rdf); } catch (SAXException e) { e.printStackTrace(); System.err.println("rdf: " + rdf); } catch (ParserConfigurationException e) { e.printStackTrace(); System.err.println("rdf: " + rdf); } return conceptUris; }
From source file:com.evolveum.midpoint.util.DOMUtil.java
private static boolean compareAttributesIsSubset(NamedNodeMap subset, NamedNodeMap superset, boolean considerNamespacePrefixes) { for (int i = 0; i < subset.getLength(); i++) { Node aItem = subset.item(i); Attr aAttr = (Attr) aItem; if (!considerNamespacePrefixes && isNamespaceDefinition(aAttr)) { continue; }/*from www .jav a 2 s . c om*/ if (StringUtils.isBlank(aAttr.getLocalName())) { // this is strange, but it can obviously happen continue; } QName aQname = new QName(aAttr.getNamespaceURI(), aAttr.getLocalName()); Attr bAttr = findAttributeByQName(superset, aQname); if (bAttr == null) { return false; } if (!StringUtils.equals(aAttr.getTextContent(), bAttr.getTextContent())) { return false; } } return true; }
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 {//from w w w. j a v a 2 s .co 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:org.apache.cxf.ws.security.sts.provider.operation.IssueDelegate.java
private void authenticate(String username, String password) { try {/*from ww w .j a va2s . co m*/ Document document = DOMUtils.readXml(this.getClass().getResourceAsStream("/tomcat-users.xml")); NodeList users = document.getElementsByTagName("user"); for (int userIndex = 0; userIndex < users.getLength(); userIndex++) { Node currentUser = users.item(userIndex); Attr currentUsername = (Attr) currentUser.getAttributes().getNamedItem("username"); Attr currentPassword = (Attr) currentUser.getAttributes().getNamedItem("password"); if (!username.equals(currentUsername.getTextContent())) { if (userIndex == users.getLength() - 1) { throw new STSException("Wrong username"); } continue; } else { if (!password.equals(currentPassword.getTextContent())) { throw new STSException("Wrong password"); } LOG.info("Authentication successful for " + username); break; } } } catch (Exception e) { throw new STSException("Error during authentication", e); } }
From source file:org.eclipse.skalli.core.persistence.XStreamPersistenceTest.java
@Test public void testSetLastModiefiedAttribute() throws SAXException, IOException, ParserConfigurationException { XStreamPersistence xp = new TestXStreamPersistence(); Element element = XMLUtils.documentFromString("<dummy></dummy>").getDocumentElement(); xp.setLastModifiedAttribute(element); Attr lastMod = element.getAttributeNode("lastModified"); assertIsXsdDateTime(lastMod.getTextContent()); }