List of usage examples for org.w3c.dom Element normalize
public void normalize();
Text
nodes in the full depth of the sub-tree underneath this Node
, including attribute nodes, into a "normal" form where only structure (e.g., elements, comments, processing instructions, CDATA sections, and entity references) separates Text
nodes, i.e., there are neither adjacent Text
nodes nor empty Text
nodes. From source file:org.toobsframework.servlet.filters.compression.CompressionFilterDAO.java
private Element loadDocument(URL url) { Document doc = null;//from w ww . j a v a 2 s . c om try { InputSource xmlInp = new InputSource(url.openStream()); DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = docBuilderFactory.newDocumentBuilder(); doc = parser.parse(xmlInp); Element root = doc.getDocumentElement(); root.normalize(); return root; } catch (SAXParseException err) { log.fatal("CompressionFilterDAO ** Parsing error" + ", line " + err.getLineNumber() + ", uri " + err.getSystemId()); log.fatal("CompressionFilterDAO error: " + err.getMessage()); } catch (SAXException e) { log.fatal("CompressionFilterDAO error: " + e); } catch (java.net.MalformedURLException mfx) { log.fatal("CompressionFilterDAO error: " + mfx); } catch (java.io.IOException e) { log.fatal("CompressionFilterDAO error: " + e); } catch (Exception pce) { log.fatal("CompressionFilterDAO error: " + pce); } return null; }
From source file:org.wso2.carbon.clustering.ClusterBuilder.java
public void build() { try {/*from ww w. j a va 2s .c om*/ log.info("Initializing cluster..."); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(clusterConfigFile); //optional, but recommended //read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work Element clusterElement = doc.getDocumentElement(); clusterElement.normalize(); System.out.println(clusterElement); if (isEnabled(clusterElement)) { String clazz = clusterElement.getAttribute("class"); Class exampleClass = Class.forName(clazz); ClusteringAgent clusteringAgent = (ClusteringAgent) exampleClass.newInstance(); // clusteringAgent.setConfigurationContext(configCtx); //loading the parameters. processParameters(clusterElement, clusteringAgent); // loading the application domains loadGroupManagement(clusteringAgent, clusterElement); // loading the members loadWellKnownMembers(clusteringAgent, clusterElement); // axisConfig.setClusteringAgent(clusteringAgent); clusteringAgent.init(); } } catch (Exception e) { String msg = "Cannot initialize cluster"; log.error(msg, e); } }
From source file:org.wso2.carbon.repository.core.config.RepositoryConfigurationProcessor.java
/** * Read XML configuration from the passed InputStream, or from the classpath. * * @param in an InputStream containing XML data, or null. * @param repositoryContext the RegistryContext to populate * * @throws RepositoryException if there's a problem */// w ww . jav a 2s .com public static void populateRepositoryConfig(InputStream in, RepositoryContext repositoryContext, RepositoryService registryService) throws RepositoryException { try { InputStream replacedStream = CarbonUtils.replaceSystemVariablesInXml(in); DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder(); Document document = documentBuilder.parse(replacedStream); Element documentElement = document.getDocumentElement(); documentElement.normalize(); NodeList rootLists = documentElement.getElementsByTagName("registryRoot"); if (rootLists != null && rootLists.getLength() > 0) { Node node = rootLists.item(0); if (node != null && node.getNodeType() == Node.ELEMENT_NODE) { String registryRoot = ((Element) node).getTextContent(); if (registryRoot != null && !registryRoot.equals(RepositoryConstants.ROOT_PATH)) { if (registryRoot.endsWith(RepositoryConstants.PATH_SEPARATOR)) { registryRoot = registryRoot.substring(0, registryRoot.length() - 1); } else if (!registryRoot.startsWith(RepositoryConstants.PATH_SEPARATOR)) { registryRoot = RepositoryConstants.ROOT_PATH + registryRoot; } } else { registryRoot = null; } repositoryContext.setRegistryRoot(registryRoot); } } NodeList readOnlyElements = documentElement.getElementsByTagName("readOnly"); if (readOnlyElements != null && readOnlyElements.getLength() > 0) { Node node = readOnlyElements.item(0); if (node != null && node.getNodeType() == Node.ELEMENT_NODE) { String isReadOnly = ((Element) node).getTextContent(); repositoryContext.setReadOnly(CarbonUtils.isReadOnlyNode() || "true".equals(isReadOnly)); } } NodeList enableCacheElements = documentElement.getElementsByTagName("enableCache"); if (enableCacheElements != null && enableCacheElements.getLength() > 0) { Node node = enableCacheElements.item(0); if (node != null && node.getNodeType() == Node.ELEMENT_NODE) { String enableCacheElement = ((Element) node).getTextContent(); repositoryContext.setCacheEnabled("true".equals(enableCacheElement)); } } SecretResolver secretResolver = SecretResolverFactory.create(documentElement, false); NodeList dbConfigElements = documentElement.getElementsByTagName("dbConfig"); for (int index = 0; index < dbConfigElements.getLength(); index++) { Node dbConfig = dbConfigElements.item(index); DataBaseConfiguration dataBaseConfiguration = new DataBaseConfiguration(); dataBaseConfiguration.setPasswordManager(secretResolver); if (dbConfig != null && dbConfig.getNodeType() == Node.ELEMENT_NODE) { Element dbConfigElement = (Element) dbConfig; String dbName = dbConfigElement.getAttribute("name"); if (dbName == null) { throw new RepositoryConfigurationException( "The database configuration name cannot be null."); } dataBaseConfiguration.setConfigName(dbName); NodeList dbConfigDataSources = dbConfigElement.getChildNodes(); for (int content = 0; content < dbConfigDataSources.getLength(); content++) { Node dbConfigNode = dbConfigDataSources.item(content); if (dbConfigNode != null && dbConfigNode.getNodeType() == Node.ELEMENT_NODE) { if (dbConfigNode.getNodeName() == "dataSource") { String dataSourceName = dbConfigNode.getTextContent(); dataBaseConfiguration.setDataSourceName(dataSourceName); try { Context context = new InitialContext(); Connection connection = null; try { connection = ((DataSource) context.lookup(dataSourceName)).getConnection(); DatabaseMetaData metaData = connection.getMetaData(); dataBaseConfiguration.setDbUrl(metaData.getURL()); dataBaseConfiguration.setUserName(metaData.getUserName()); } finally { if (connection != null) { connection.close(); } } } catch (NamingException ignored) { log.warn("Unable to look-up JNDI name " + dataSourceName); } catch (SQLException e) { e.printStackTrace(); throw new RepositoryDBException("Unable to connect to Data Source", e); } } else { if (dbConfigNode.getNodeName() == "userName") { dataBaseConfiguration.setUserName(dbConfigNode.getTextContent()); } else if (dbConfigNode.getNodeName() == "password") { dataBaseConfiguration.setPassWord(dbConfigNode.getTextContent()); } else if (dbConfigNode.getNodeName() == "url") { String dbUrl = dbConfigNode.getTextContent(); if (dbUrl != null) { if (dbUrl.contains(CarbonConstants.CARBON_HOME_PARAMETER)) { File carbonHomeDir; carbonHomeDir = new File(CarbonUtils.getCarbonHome()); String path = carbonHomeDir.getPath(); path = path.replaceAll(Pattern.quote("\\"), "/"); if (carbonHomeDir.exists() && carbonHomeDir.isDirectory()) { dbUrl = dbUrl.replaceAll( Pattern.quote(CarbonConstants.CARBON_HOME_PARAMETER), path); } else { log.warn("carbon home invalid"); String[] tempStrings1 = dbUrl.split( Pattern.quote(CarbonConstants.CARBON_HOME_PARAMETER)); String tempUrl = tempStrings1[1]; String[] tempStrings2 = tempUrl.split("/"); for (int i = 0; i < tempStrings2.length - 1; i++) { dbUrl = tempStrings1[0] + tempStrings2[i] + "/"; } dbUrl = dbUrl + tempStrings2[tempStrings2.length - 1]; } } } dataBaseConfiguration.setDbUrl(dbUrl); } else if (dbConfigNode.getNodeName() == "maxWait") { dataBaseConfiguration.setMaxWait(dbConfigNode.getTextContent()); } else if (dbConfigNode.getNodeName() == "maxActive") { dataBaseConfiguration.setMaxActive(dbConfigNode.getTextContent()); } else if (dbConfigNode.getNodeName() == "minIdle") { dataBaseConfiguration.setMinIdle(dbConfigNode.getTextContent()); } else if (dbConfigNode.getNodeName() == "driverName") { dataBaseConfiguration.setDriverName(dbConfigNode.getTextContent()); } } } } repositoryContext.addDBConfig(dbName, dataBaseConfiguration); } } NodeList staticConfigNodes = documentElement.getElementsByTagName("staticConfiguration"); if (staticConfigNodes != null && staticConfigNodes.getLength() > 0) { Node staticConfigNode = staticConfigNodes.item(0); NodeList staticConfigItems = staticConfigNode.getChildNodes(); for (int index = 0; index < staticConfigItems.getLength(); index++) { Node staticConfig = staticConfigItems.item(index); if (staticConfig != null && staticConfig.getNodeType() == Node.ELEMENT_NODE) { if (staticConfig.getNodeName().equals("versioningProperties")) { String versioningProperties = staticConfig.getTextContent(); StaticConfiguration.setVersioningProperties(versioningProperties.equals("true")); } else if (staticConfig.getNodeName().equals("profilesPath")) { String profilesPath = staticConfig.getTextContent(); if (!profilesPath.startsWith(RepositoryConstants.PATH_SEPARATOR)) { profilesPath = RepositoryConstants.PATH_SEPARATOR + profilesPath; } if (profilesPath.endsWith(RepositoryConstants.PATH_SEPARATOR)) { profilesPath = profilesPath.substring(0, (profilesPath.length() - 1)); } if (profilesPath != null) { if (profilesPath.startsWith(RepositoryConstants.CONFIG_REGISTRY_BASE_PATH)) { repositoryContext.setProfilesPath(profilesPath); } else { repositoryContext.setProfilesPath( RepositoryConstants.CONFIG_REGISTRY_BASE_PATH + profilesPath); } } } else if (staticConfig.getNodeName().equals("servicePath")) { String servicePath = staticConfig.getTextContent(); if (!servicePath.startsWith(RepositoryConstants.PATH_SEPARATOR)) { servicePath = RepositoryConstants.PATH_SEPARATOR + servicePath; } if (servicePath.endsWith(RepositoryConstants.PATH_SEPARATOR)) { servicePath = servicePath.substring(0, (servicePath.length() - 1)); } if (servicePath != null) { if (servicePath.startsWith(RepositoryConstants.GOVERNANCE_REGISTRY_BASE_PATH)) { repositoryContext.setServicePath(servicePath); } else { repositoryContext.setServicePath( RepositoryConstants.GOVERNANCE_REGISTRY_BASE_PATH + servicePath); } } } } } } NodeList currentDBConfigs = documentElement.getElementsByTagName("currentDBConfig"); if (currentDBConfigs == null) { throw new RepositoryConfigurationException("The current database configuration is not defined."); } String currentConfigName = currentDBConfigs.item(0).getTextContent(); readRemoteInstances(documentElement, repositoryContext, secretResolver); readMounts(documentElement, repositoryContext); DataBaseConfiguration dbConfiguration = repositoryContext.selectDBConfig(currentConfigName); repositoryContext.setDefaultDataBaseConfiguration(dbConfiguration); NodeList versionConfigList = documentElement.getElementsByTagName("versionResourcesOnChange"); if (versionConfigList != null && versionConfigList.getLength() > 0) { Node versionConfig = versionConfigList.item(0); if (versionConfig != null && "true".equals(versionConfig.getTextContent())) { repositoryContext.setVersionOnChange(true); } else { repositoryContext.setVersionOnChange(false); } } initializeHandlers(documentElement, repositoryContext); // process query processor configuration NodeList queryProcessors = documentElement.getElementsByTagName("queryProcessor"); for (int index = 0; index < queryProcessors.getLength(); index++) { QueryProcessorConfiguration queryProcessorConfiguration = new QueryProcessorConfiguration(); Node queryProcessorNode = queryProcessors.item(index); NodeList queryProcessorChildren = queryProcessorNode.getChildNodes(); for (int childIndex = 0; childIndex < queryProcessorChildren.getLength(); childIndex++) { Node queryProcessorChild = queryProcessorChildren.item(childIndex); if (queryProcessorChild != null && queryProcessorChild.getNodeType() == Node.ELEMENT_NODE) { if (queryProcessorChild.getNodeName() == "queryType") { queryProcessorConfiguration.setQueryType(queryProcessorChild.getTextContent()); } else if (queryProcessorChild.getNodeName() == "processor") { queryProcessorConfiguration.setProcessorClassName(queryProcessorChild.getTextContent()); } } } repositoryContext.addQueryProcessor(queryProcessorConfiguration); } } catch (SAXException e1) { throw new RepositoryInitException(e1.getMessage()); } catch (IOException e1) { throw new RepositoryInitException(e1.getMessage()); } catch (ParserConfigurationException e1) { throw new RepositoryInitException(e1.getMessage()); } catch (CarbonException e) { log.error("An error occurred during system variable replacement", e); } }
From source file:ro.agrade.jira.qanda.dao.GenericDelegatorLoader.java
/** * Add the associations "entity name"-"group name" from the xml file * represented by the ResourceHandler rh to the group cache from the model * reader modelGroupR. The code is a part from getGroupCache() method from * ModelGroupReader class./* w w w. j av a 2 s . c o m*/ * * @param modelGroupReader The model group reader. * @param resourceHandler The resource handler for entity groups associations. * @throws OfbizDataException if an error occurs when adding groups to * group cache */ private void addGroupsToGroupCache(ModelGroupReader modelGroupReader, ResourceHandler resourceHandler) throws OfbizDataException { if (modelGroupReader == null || resourceHandler == null) { LOG.warn(String.format("Null timereport group reader or resource " + "handler in addGroupsToGroupCache() method." + " Model reader: %s resource handler: %s", modelGroupReader, resourceHandler)); return; } try { Map<?, ?> groupCache = modelGroupReader.getGroupCache(); Document document; synchronized (ModelGroupReader.class) { try { document = resourceHandler.getDocument(); } catch (GenericConfigException e) { String msg = "Error loading entity group timereport"; LOG.error(msg, e); throw new OfbizDataException(msg, e); } if (document == null) { String msg = String.format("Could not get document for %s", resourceHandler); LOG.error(msg); throw new OfbizDataException(msg); } Element docElement = document.getDocumentElement(); if (docElement == null) { String msg = "NULL doc element."; LOG.error(msg); throw new OfbizDataException(msg); } docElement.normalize(); Node curChild = docElement.getFirstChild(); if (curChild != null) { do { if (curChild.getNodeType() == Node.ELEMENT_NODE && "entity-group".equals(curChild.getNodeName())) { Element curEntity = (Element) curChild; String entityName = UtilXml.checkEmpty(curEntity.getAttribute("entity")); String groupName = UtilXml.checkEmpty(curEntity.getAttribute("group")); if (groupName == null || entityName == null) { continue; } safelyMapAdd(groupCache, entityName, groupName); } } while ((curChild = curChild.getNextSibling()) != null); } else { LOG.warn("[addGroupsToGroupCache()] No child nodes found."); } } } catch (Exception ex) { String msg = String.format("Got exception when adding groups " + "from resource handler: %s", resourceHandler); LOG.error(msg, ex); throw new OfbizDataException(msg, ex); } }
From source file:ro.agrade.jira.qanda.dao.GenericDelegatorLoader.java
/** * Add the model entities from the xml file represented by the * ResourceHandler rhEntity to the entity cache from the model reader * modelR. The code is(with little changes) a part from getEntityCache() * method in ModelReader class.//from w ww. j a va 2 s . c o m * * @param modelReader The model reader. * @param resourceHandler The resource handler. * @param loaderEnt The loader name for the xml for entities. * @param locationEnt The location for the xml file for entities. * @throws OfbizDataException if an error occurs when adding entities to * entity cache */ private void addEntitiesToEntityCache(ModelReader modelReader, ResourceHandler resourceHandler, String loaderEnt, String locationEnt) throws OfbizDataException { if (modelReader == null || resourceHandler == null) { LOG.warn( String.format("Null reader or resource handler" + " in addEntitiesToEntityCache() method. Model" + " reader: %s Resource handler: %s", modelReader, resourceHandler)); return; } try { Document document; Map<String, ModelEntity> entityCache = modelReader.getEntityCache(); List<ModelViewEntity> tempViewEntityList = new LinkedList<ModelViewEntity>(); Hashtable<String, String> docElementValues = new Hashtable<String, String>(); synchronized (ModelReader.class) { try { document = resourceHandler.getDocument(); } catch (GenericConfigException e) { String msg = "Error getting document from resource handler"; LOG.error(msg); throw new GenericEntityConfException(msg, e); } if (document == null) { String msg = String.format("Could not get document for %s", resourceHandler); LOG.error(msg); throw new OfbizDataException(msg); } Element docElement = document.getDocumentElement(); if (docElement == null) { String msg = "NULL doc element."; LOG.error(msg); throw new OfbizDataException(msg); } docElement.normalize(); Node curChild = docElement.getFirstChild(); int i = 0; if (curChild != null) { do { boolean isEntity = "entity".equals(curChild.getNodeName()); boolean isViewEntity = "view-entity".equals(curChild.getNodeName()); if ((isEntity || isViewEntity) && curChild.getNodeType() == Node.ELEMENT_NODE) { i++; Element curEntity = (Element) curChild; String entityName = UtilXml.checkEmpty(curEntity.getAttribute("entity-name")); // check to see if entity with same name has already // been read if (entityCache.containsKey(entityName)) { if (LOG.isDebugEnabled()) { LOG.debug(String.format("Entity %s is defined more than once, most " + "recent will overwrite previous definition", entityName)); } } // add entity to entityResourceHandlerMap map modelReader.addEntityToResourceHandler(entityName, loaderEnt, locationEnt); ModelEntity entity; if (isEntity) { entity = createModelEntity(modelReader, curEntity, docElement, null, docElementValues); if (LOG.isDebugEnabled()) { LOG.debug(String.format("[Entity]: # %d: %s", i, entityName)); } } else { entity = createModelViewEntity(modelReader, curEntity, docElement, null, docElementValues); // put the view entity in a list to get ready // for the second pass to populate fields... tempViewEntityList.add((ModelViewEntity) entity); if (LOG.isDebugEnabled()) { String msg = String.format("[ViewEntity]: # %d: %s", i, entityName); LOG.debug(msg); } } if (entity != null) { safelyMapAdd(entityCache, entityName, entity); } else { LOG.warn(String.format("Could not create entity " + "for entityName: %s", entityName)); } } } while ((curChild = curChild.getNextSibling()) != null); } else { LOG.warn("No child nodes found."); } modelReader.rebuildResourceHandlerEntities(); // do a pass on all of the view entities now that all of the // entities have loaded and populate the fields for (ModelViewEntity me : tempViewEntityList) { me.populateFields(entityCache); } LOG.debug("FINISHED LOADING ENTITIES."); } } catch (Exception ex) { String msg = String.format("Got exception when adding entities " + "from resource handler: %s", resourceHandler); LOG.error(msg, ex); throw new OfbizDataException(msg, ex); } }