List of usage examples for javax.xml.parsers DocumentBuilder setErrorHandler
public abstract void setErrorHandler(ErrorHandler eh);
From source file:net.sourceforge.eclipsetrader.core.internal.XMLRepository.java
public XMLRepository() { File file = new File(Platform.getLocation().toFile(), "securities.xml"); //$NON-NLS-1$ if (file.exists() == true) { log.info("Loading securities"); //$NON-NLS-1$ try {/* ww w . j a va 2s . c o m*/ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(errorHandler); Document document = builder.parse(file); Node firstNode = document.getFirstChild(); securitiesNextId = new Integer(firstNode.getAttributes().getNamedItem("nextId").getNodeValue()); //$NON-NLS-1$ if (firstNode.getAttributes().getNamedItem("nextGroupId") != null) //$NON-NLS-1$ securitiesGroupNextId = new Integer( firstNode.getAttributes().getNamedItem("nextGroupId").getNodeValue()); //$NON-NLS-1$ NodeList childNodes = firstNode.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node item = childNodes.item(i); String nodeName = item.getNodeName(); if (nodeName.equalsIgnoreCase("security")) //$NON-NLS-1$ { Security obj = loadSecurity(item.getChildNodes()); obj.setRepository(this); securitiesMap.put(obj.getId(), obj); allSecurities().add(obj); } else if (nodeName.equalsIgnoreCase("group")) //$NON-NLS-1$ { SecurityGroup obj = loadSecurityGroup(item.getChildNodes()); obj.setRepository(this); allSecurityGroups().add(obj); } } } catch (Exception e) { log.error(e.toString(), e); } } file = new File(Platform.getLocation().toFile(), "watchlists.xml"); //$NON-NLS-1$ if (file.exists() == true) { log.info("Loading watchlists"); //$NON-NLS-1$ try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(errorHandler); Document document = builder.parse(file); Node firstNode = document.getFirstChild(); watchlistsNextId = new Integer(firstNode.getAttributes().getNamedItem("nextId").getNodeValue()); //$NON-NLS-1$ NodeList childNodes = firstNode.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node item = childNodes.item(i); String nodeName = item.getNodeName(); if (nodeName.equalsIgnoreCase("watchlist")) //$NON-NLS-1$ { Watchlist obj = loadWatchlist(item.getChildNodes()); obj.setRepository(this); watchlistsMap.put(obj.getId(), obj); allWatchlists().add(obj); } } } catch (Exception e) { log.error(e.toString(), e); } } file = new File(Platform.getLocation().toFile(), "charts.xml"); //$NON-NLS-1$ if (file.exists() == true) { log.info("Loading charts"); //$NON-NLS-1$ try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(errorHandler); Document document = builder.parse(file); Node firstNode = document.getFirstChild(); chartsNextId = new Integer(firstNode.getAttributes().getNamedItem("nextId").getNodeValue()); //$NON-NLS-1$ NodeList childNodes = firstNode.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node item = childNodes.item(i); String nodeName = item.getNodeName(); if (nodeName.equalsIgnoreCase("chart")) //$NON-NLS-1$ { Chart obj = loadChart(item.getChildNodes()); if (obj.getSecurity() != null) { obj.setRepository(this); chartsMap.put(obj.getId(), obj); allCharts().add(obj); } } } } catch (Exception e) { log.error(e.toString(), e); } } boolean needToSave = false; for (Iterator iter = allSecurities().iterator(); iter.hasNext();) { Security security = (Security) iter.next(); file = new File(Platform.getLocation().toFile(), "charts/" + String.valueOf(security.getId()) + ".xml"); //$NON-NLS-1$ //$NON-NLS-2$ if (file.exists()) { Chart obj = loadChart(security.getId()); if (obj.getSecurity() != null) { if (obj.getId().intValue() > chartsNextId.intValue()) chartsNextId = getNextId(obj.getId()); obj.setRepository(this); chartsMap.put(obj.getId(), obj); allCharts().add(obj); file.delete(); needToSave = true; } } } if (needToSave) saveCharts(); file = new File(Platform.getLocation().toFile(), "news.xml"); //$NON-NLS-1$ if (file.exists() == true) { log.info("Loading news"); //$NON-NLS-1$ try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(errorHandler); Document document = builder.parse(file); Calendar limit = Calendar.getInstance(); limit.add(Calendar.DATE, -CorePlugin.getDefault().getPreferenceStore().getInt(CorePlugin.PREFS_NEWS_DATE_RANGE)); Node firstNode = document.getFirstChild(); NodeList childNodes = firstNode.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node item = childNodes.item(i); String nodeName = item.getNodeName(); if (nodeName.equalsIgnoreCase("news")) //$NON-NLS-1$ { NewsItem obj = loadNews(item.getChildNodes()); if (obj.getDate().before(limit.getTime())) continue; obj.setRepository(this); allNews().add(obj); } } } catch (Exception e) { log.error(e.toString(), e); } } file = new File(Platform.getLocation().toFile(), "accounts.xml"); //$NON-NLS-1$ if (file.exists() == true) { log.info("Loading accounts"); //$NON-NLS-1$ try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(errorHandler); Document document = builder.parse(file); Node firstNode = document.getFirstChild(); accountNextId = new Integer(firstNode.getAttributes().getNamedItem("nextId").getNodeValue()); //$NON-NLS-1$ accountGroupNextId = new Integer( firstNode.getAttributes().getNamedItem("nextGroupId").getNodeValue()); //$NON-NLS-1$ NodeList childNodes = firstNode.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node item = childNodes.item(i); String nodeName = item.getNodeName(); if (nodeName.equalsIgnoreCase("account")) //$NON-NLS-1$ { Account obj = loadAccount(item.getChildNodes(), null); obj.setRepository(this); } else if (nodeName.equalsIgnoreCase("group")) //$NON-NLS-1$ { AccountGroup obj = loadAccountGroup(item.getChildNodes(), null); obj.setRepository(this); } } } catch (Exception e) { log.error(e.toString(), e); } } file = new File(Platform.getLocation().toFile(), "events.xml"); //$NON-NLS-1$ if (file.exists() == true) { log.info("Loading events"); //$NON-NLS-1$ try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(errorHandler); Document document = builder.parse(file); Node firstNode = document.getFirstChild(); NodeList childNodes = firstNode.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node item = childNodes.item(i); String nodeName = item.getNodeName(); if (nodeName.equalsIgnoreCase("event")) //$NON-NLS-1$ { Event obj = loadEvent(item.getChildNodes()); obj.setRepository(this); allEvents().add(obj); } } } catch (Exception e) { log.error(e.toString(), e); } } file = new File(Platform.getLocation().toFile(), "orders.xml"); //$NON-NLS-1$ if (file.exists() == true) { log.info("Loading orders"); //$NON-NLS-1$ try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setErrorHandler(errorHandler); Document document = builder.parse(file); Node firstNode = document.getFirstChild(); orderNextId = new Integer(firstNode.getAttributes().getNamedItem("nextId").getNodeValue()); //$NON-NLS-1$ NodeList childNodes = firstNode.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node item = childNodes.item(i); String nodeName = item.getNodeName(); if (nodeName.equalsIgnoreCase("order")) //$NON-NLS-1$ { Order obj = loadOrder(item.getChildNodes()); obj.setRepository(this); allOrders().add(obj); } } } catch (Exception e) { log.error(e.toString(), e); } } eventNextId = new Integer(allEvents().size() + 1); tradingRepository = new TradingSystemRepository(this); }
From source file:com.amalto.workbench.utils.Util.java
public static Document parse(String xmlString, String schema) throws Exception { // parse//from w w w . j a v a 2s . c o m Document d = null; SAXErrorHandler seh = new SAXErrorHandler(); try { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); documentBuilderFactory.setValidating((schema != null)); documentBuilderFactory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", //$NON-NLS-1$ "http://www.w3.org/2001/XMLSchema");//$NON-NLS-1$ if (schema != null) { documentBuilderFactory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource", //$NON-NLS-1$ new InputSource(new StringReader(schema))); } DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); documentBuilder.setErrorHandler(seh); if (xmlString == null || xmlString.length() == 0 || xmlString.matches("\\s+")) { return d; } d = documentBuilder.parse(new InputSource(new StringReader(xmlString))); if (schema != null) { String errors = seh.getErrors(); if (!errors.equals("")) {//$NON-NLS-1$ String err = Messages.Util_12 + errors + Messages.Util_13; throw new Exception(err); } } return d; } catch (Exception e) { log.error(e.getMessage(), e); String err = Messages.Util_14 + Messages.Util_15 + e.getClass().getName() + Messages.Util_16 + e.getLocalizedMessage() + Messages.Util_17 + xmlString; throw new Exception(err); } }
From source file:ch.entwine.weblounge.common.impl.site.SiteImpl.java
/** * Initializes the site components like modules, templates, actions etc. * /* w w w .j av a 2 s.c o m*/ * @throws Exception * if initialization fails */ private void initializeSiteComponents() throws Exception { logger.debug("Initializing site '{}'", this); final Bundle bundle = bundleContext.getBundle(); // Load i18n dictionary Enumeration<URL> i18nEnum = bundle.findEntries("site/i18n", "*.xml", true); while (i18nEnum != null && i18nEnum.hasMoreElements()) { i18n.addDictionary(i18nEnum.nextElement()); } // Prepare schema validator SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); URL schemaUrl = SiteImpl.class.getResource("/xsd/module.xsd"); Schema moduleSchema = schemaFactory.newSchema(schemaUrl); // Set up the document builder DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); docBuilderFactory.setSchema(moduleSchema); docBuilderFactory.setNamespaceAware(true); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); // Load the modules final Enumeration<URL> e = bundle.findEntries("site", "module.xml", true); if (e != null) { while (e.hasMoreElements()) { URL moduleXmlUrl = e.nextElement(); int endIndex = moduleXmlUrl.toExternalForm().lastIndexOf('/'); URL moduleUrl = new URL(moduleXmlUrl.toExternalForm().substring(0, endIndex)); logger.debug("Loading module '{}' for site '{}'", moduleXmlUrl, this); // Load and validate the module descriptor ValidationErrorHandler errorHandler = new ValidationErrorHandler(moduleXmlUrl); docBuilder.setErrorHandler(errorHandler); Document moduleXml = docBuilder.parse(moduleXmlUrl.openStream()); if (errorHandler.hasErrors()) { logger.error("Errors found while validating module descriptor {}. Site '{}' is not loaded", moduleXml, this); throw new IllegalStateException("Errors found while validating module descriptor " + moduleXml); } // We need the module id even if the module initialization fails to log // a proper error message Node moduleNode = moduleXml.getFirstChild(); String moduleId = moduleNode.getAttributes().getNamedItem("id").getNodeValue(); Module module; try { module = ModuleImpl.fromXml(moduleNode); logger.debug("Module '{}' loaded for site '{}'", module, this); } catch (Throwable t) { logger.error("Error loading module '{}' of site {}", moduleId, identifier); if (t instanceof Exception) throw (Exception) t; throw new Exception(t); } // If module is disabled, don't add it to the site if (!module.isEnabled()) { logger.info("Found disabled module '{}' in site '{}'", module, this); continue; } // Make sure there is only one module with this identifier if (modules.containsKey(module.getIdentifier())) { logger.warn("A module with id '{}' is already registered in site '{}'", module.getIdentifier(), identifier); logger.error("Module '{}' is not registered due to conflicting identifier", module.getIdentifier()); continue; } // Check inter-module compatibility for (Module m : modules.values()) { // Check actions for (Action a : m.getActions()) { for (Action action : module.getActions()) { if (action.getIdentifier().equals(a.getIdentifier())) { logger.warn("Module '{}' of site '{}' already defines an action with id '{}'", new String[] { m.getIdentifier(), identifier, a.getIdentifier() }); } else if (action.getPath().equals(a.getPath())) { logger.warn("Module '{}' of site '{}' already defines an action at '{}'", new String[] { m.getIdentifier(), identifier, a.getPath() }); logger.error( "Module '{}' of site '{}' is not registered due to conflicting mountpoints", m.getIdentifier(), identifier); continue; } } } // Check image styles for (ImageStyle s : m.getImageStyles()) { for (ImageStyle style : module.getImageStyles()) { if (style.getIdentifier().equals(s.getIdentifier())) { logger.warn("Module '{}' of site '{}' already defines an image style with id '{}'", new String[] { m.getIdentifier(), identifier, s.getIdentifier() }); } } } // Check jobs for (Job j : m.getJobs()) { for (Job job : module.getJobs()) { if (job.getIdentifier().equals(j.getIdentifier())) { logger.warn("Module '{}' of site '{}' already defines a job with id '{}'", new String[] { m.getIdentifier(), identifier, j.getIdentifier() }); } } } } addModule(module); // Do this as last step since we don't want to have i18n dictionaries of // an invalid or disabled module in the site String i18nPath = UrlUtils.concat(moduleUrl.getPath(), "i18n"); i18nEnum = bundle.findEntries(i18nPath, "*.xml", true); while (i18nEnum != null && i18nEnum.hasMoreElements()) { i18n.addDictionary(i18nEnum.nextElement()); } } } else { logger.debug("Site '{}' has no modules", this); } // Look for a job scheduler logger.debug("Signing up for a job scheduling services"); schedulingServiceTracker = new SchedulingServiceTracker(bundleContext, this); schedulingServiceTracker.open(); // Load the tests if (!Environment.Production.equals(environment)) integrationTests = loadIntegrationTests(); else logger.info("Skipped loading of integration tests due to environment '{}'", environment); siteInitialized = true; logger.info("Site '{}' initialized", this); }
From source file:de.interactive_instruments.ShapeChange.Options.java
public void loadConfiguration() throws ShapeChangeAbortException { InputStream configStream = null; if (configFile == null) { // load minimal configuration, if no configuration file has been // provided configFile = "/config/minimal.xml"; configStream = getClass().getResourceAsStream(configFile); if (configStream == null) { configFile = "src/main/resources" + configFile; File file = new File(configFile); if (file.exists()) try { configStream = new FileInputStream(file); } catch (FileNotFoundException e1) { throw new ShapeChangeAbortException("Minimal configuration file not found: " + configFile); }//from w w w. ja v a 2s . com else { URL url; String configURL = "http://shapechange.net/resources/config/minimal.xml"; try { url = new URL(configURL); configStream = url.openStream(); } catch (MalformedURLException e) { throw new ShapeChangeAbortException("Minimal configuration file not accessible from: " + configURL + " (malformed URL)"); } catch (IOException e) { throw new ShapeChangeAbortException( "Minimal configuration file not accessible from: " + configURL + " (IO error)"); } } } } else { File file = new File(configFile); if (file == null || !file.exists()) { try { configStream = (new URL(configFile)).openStream(); } catch (MalformedURLException e) { throw new ShapeChangeAbortException( "No configuration file found at " + configFile + " (malformed URL)"); } catch (IOException e) { throw new ShapeChangeAbortException( "No configuration file found at " + configFile + " (IO exception)"); } } else { try { configStream = new FileInputStream(file); } catch (FileNotFoundException e) { throw new ShapeChangeAbortException("No configuration file found at " + configFile); } } if (configStream == null) { throw new ShapeChangeAbortException("No configuration file found at " + configFile); } } DocumentBuilder builder = null; ShapeChangeErrorHandler handler = null; try { System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl"); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(true); factory.setFeature("http://apache.org/xml/features/validation/schema", true); factory.setIgnoringElementContentWhitespace(true); factory.setIgnoringComments(true); factory.setXIncludeAware(true); factory.setFeature("http://apache.org/xml/features/xinclude/fixup-base-uris", false); builder = factory.newDocumentBuilder(); handler = new ShapeChangeErrorHandler(); builder.setErrorHandler(handler); } catch (FactoryConfigurationError e) { throw new ShapeChangeAbortException("Unable to get a document builder factory."); } catch (ParserConfigurationException e) { throw new ShapeChangeAbortException("XML Parser was unable to be configured."); } // parse file try { Document document = builder.parse(configStream); if (handler.errorsFound()) { throw new ShapeChangeAbortException("Invalid configuration file."); } // parse input element specific content NodeList nl = document.getElementsByTagName("input"); Element inputElement = (Element) nl.item(0); if (inputElement.hasAttribute("id")) { inputId = inputElement.getAttribute("id").trim(); if (inputId.length() == 0) { inputId = null; } } else { inputId = Options.INPUTELEMENTID; } Map<String, String> inputParameters = new HashMap<String, String>(); nl = inputElement.getElementsByTagName("parameter"); for (int j = 0; j < nl.getLength(); j++) { Element e = (Element) nl.item(j); String key = e.getAttribute("name"); String val = e.getAttribute("value"); inputParameters.put(key, val); } Map<String, String> stereotypeAliases = new HashMap<String, String>(); nl = inputElement.getElementsByTagName("StereotypeAlias"); for (int j = 0; j < nl.getLength(); j++) { Element e = (Element) nl.item(j); String key = e.getAttribute("alias"); String val = e.getAttribute("wellknown"); // case shall be ignored key = key.toLowerCase(); val = val.toLowerCase(); stereotypeAliases.put(key, val); } Map<String, String> tagAliases = new HashMap<String, String>(); nl = inputElement.getElementsByTagName("TagAlias"); for (int j = 0; j < nl.getLength(); j++) { Element e = (Element) nl.item(j); String key = e.getAttribute("alias"); String val = e.getAttribute("wellknown"); // case not to be ignored for tagged values at the moment // key = key.toLowerCase(); // val = val.toLowerCase(); tagAliases.put(key, val); } Map<String, String> descriptorSources = new HashMap<String, String>(); nl = inputElement.getElementsByTagName("DescriptorSource"); for (int j = 0; j < nl.getLength(); j++) { Element e = (Element) nl.item(j); String key = e.getAttribute("descriptor"); String val = e.getAttribute("source"); // case shall be ignored for descriptor and source key = key.toLowerCase(); val = val.toLowerCase(); if (val.equals("sc:extract")) { String s = e.getAttribute("token"); val += "#" + (s == null ? "" : s); } else if (val.equals("tag")) { String s = e.getAttribute("tag"); val += "#" + (s == null ? "" : s); } descriptorSources.put(key, val); } Map<String, PackageInfoConfiguration> packageInfos = parsePackageInfos(inputElement); this.inputConfig = new InputConfiguration(inputId, inputParameters, stereotypeAliases, tagAliases, descriptorSources, packageInfos); // parse dialog specific parameters nl = document.getElementsByTagName("dialog"); if (nl != null && nl.getLength() != 0) { for (int k = 0; k < nl.getLength(); k++) { Node node = nl.item(k); if (node.getNodeType() == Node.ELEMENT_NODE) { Element dialogElement = (Element) node; this.dialogParameters = parseParameters(dialogElement, "parameter"); } } } // parse log specific parameters nl = document.getElementsByTagName("log"); if (nl != null && nl.getLength() != 0) { for (int k = 0; k < nl.getLength(); k++) { Node node = nl.item(k); if (node.getNodeType() == Node.ELEMENT_NODE) { Element logElement = (Element) node; this.logParameters = parseParameters(logElement, "parameter"); } } } // add standard rules, just so that configured rules can be // validated addStandardRules(); // Load transformer configurations (if any are provided in the // configuration file) Map<String, TransformerConfiguration> transformerConfigs = parseTransformerConfigurations(document); // Load target configurations this.targetConfigs = parseTargetConfigurations(document); this.resetFields(); // this.resetUponLoadFlag = false; // TBD discuss if there's a better way to support rule and // requirements matching for the input model // TBD apparently the matching requires all // applicable encoding rules to be known up front for (TargetConfiguration tgtConfig : targetConfigs) { // System.out.println(tgtConfig); String className = tgtConfig.getClassName(); String mode = tgtConfig.getProcessMode().name(); // set targets and their mode; if a target occurs multiple // times, keep the enabled one(s) if (!this.fTargets.containsKey(className)) { addTarget(className, mode); } else { if (this.fTargets.get(className).equals(ProcessMode.disabled)) { // set targets and their mode; if a target occurs // multiple times, keep the enabled one(s) addTarget(className, mode); } } // ensure that we have all the rules from all non-disabled // targets // we repeat this for the same target (if it is not disabled) to // ensure that we get the union of all encoding rules if (!tgtConfig.getProcessMode().equals(ProcessMode.disabled)) { for (ProcessRuleSet prs : tgtConfig.getRuleSets().values()) { String nam = prs.getName(); String ext = prs.getExtendedRuleSetName(); addExtendsEncRule(nam, ext); if (prs.hasAdditionalRules()) { for (String rule : prs.getAdditionalRules()) { addRule(rule, nam); } } } } /* * looks like we also need parameters like defaultEncodingRule * !!! IF THERE ARE DIFFERENT DEFAULT ENCODING RULES FOR * DIFFERENT TARGETS (WITH SAME CLASS) THIS WONT WORK!!! */ for (String paramName : tgtConfig.getParameters().keySet()) { setParameter(className, paramName, tgtConfig.getParameters().get(paramName)); } // in order for the input model load not to produce warnings, // we also need to load the map entries if (tgtConfig instanceof TargetXmlSchemaConfiguration) { TargetXmlSchemaConfiguration config = (TargetXmlSchemaConfiguration) tgtConfig; // add xml schema namespace information for (XmlNamespace xns : config.getXmlNamespaces()) { addNamespace(xns.getNsabr(), xns.getNs(), xns.getLocation()); // if (xns.getLocation() != null) { addSchemaLocation(xns.getNs(), xns.getLocation()); // } } // add xsd map entries for (XsdMapEntry xsdme : config.getXsdMapEntries()) { for (String xsdEncodingRule : xsdme.getEncodingRules()) { String type = xsdme.getType(); String xmlPropertyType = xsdme.getXmlPropertyType(); String xmlElement = xsdme.getXmlElement(); String xmlTypeContent = xsdme.getXmlTypeContent(); String xmlTypeNilReason = xsdme.getXmlTypeNilReason(); String xmlType = xsdme.getXmlType(); String xmlTypeType = xsdme.getXmlTypeType(); String xmlAttribute = xsdme.getXmlAttribute(); String xmlAttributeGroup = xsdme.getXmlAttributeGroup(); if (xmlPropertyType != null) { if (xmlPropertyType.equals("_P_") && xmlElement != null) { addTypeMapEntry(type, xsdEncodingRule, "propertyType", xmlElement); } else if (xmlPropertyType.equals("_MP_") && xmlElement != null) { addTypeMapEntry(type, xsdEncodingRule, "metadataPropertyType", xmlElement); } else { addTypeMapEntry(type, xsdEncodingRule, "direct", xmlPropertyType, xmlTypeType + "/" + xmlTypeContent, xmlTypeNilReason); } } if (xmlElement != null) { addElementMapEntry(type, xsdEncodingRule, "direct", xmlElement); } if (xmlType != null) { addBaseMapEntry(type, xsdEncodingRule, "direct", xmlType, xmlTypeType + "/" + xmlTypeContent); } if (xmlAttribute != null) { addAttributeMapEntry(type, xsdEncodingRule, xmlAttribute); } if (xmlAttributeGroup != null) { addAttributeGroupMapEntry(type, xsdEncodingRule, xmlAttributeGroup); } } } } else { // add map entries for Target (no need to do this for // transformers) for (ProcessMapEntry pme : tgtConfig.getMapEntries()) { addTargetTypeMapEntry(tgtConfig.getClassName(), pme.getType(), pme.getRule(), pme.getTargetType(), pme.getParam()); } } } // create "tree" for (TargetConfiguration tgtConfig : targetConfigs) { for (String inputIdref : tgtConfig.getInputIds()) { if (inputIdref.equals(getInputId())) { this.inputTargetConfigs.add(tgtConfig); } else { transformerConfigs.get(inputIdref).addTarget(tgtConfig); } } } for (TransformerConfiguration trfConfig : transformerConfigs.values()) { String inputIdref = trfConfig.getInputId(); if (inputIdref.equals(getInputId())) { this.inputTransformerConfigs.add(trfConfig); } else { transformerConfigs.get(inputIdref).addTransformer(trfConfig); } } // Determine constraint creation handling parameters: String classTypesToCreateConstraintsFor = parameter("classTypesToCreateConstraintsFor"); if (classTypesToCreateConstraintsFor != null) { classTypesToCreateConstraintsFor = classTypesToCreateConstraintsFor.trim(); if (classTypesToCreateConstraintsFor.length() > 0) { String[] stereotypes = classTypesToCreateConstraintsFor.split("\\W*,\\W*"); this.classTypesToCreateConstraintsFor = new HashSet<Integer>(); for (String stereotype : stereotypes) { String sForCons = stereotype.toLowerCase(); if (sForCons.equals("enumeration")) { this.classTypesToCreateConstraintsFor.add(new Integer(ENUMERATION)); } else if (sForCons.equals("codelist")) { this.classTypesToCreateConstraintsFor.add(new Integer(CODELIST)); } else if (sForCons.equals("schluesseltabelle")) { this.classTypesToCreateConstraintsFor.add(new Integer(OKSTRAKEY)); } else if (sForCons.equals("fachid")) { this.classTypesToCreateConstraintsFor.add(new Integer(OKSTRAFID)); } else if (sForCons.equals("datatype")) { this.classTypesToCreateConstraintsFor.add(new Integer(DATATYPE)); } else if (sForCons.equals("union")) { this.classTypesToCreateConstraintsFor.add(new Integer(UNION)); } else if (sForCons.equals("featureconcept")) { this.classTypesToCreateConstraintsFor.add(new Integer(FEATURECONCEPT)); } else if (sForCons.equals("attributeconcept")) { this.classTypesToCreateConstraintsFor.add(new Integer(ATTRIBUTECONCEPT)); } else if (sForCons.equals("valueconcept")) { this.classTypesToCreateConstraintsFor.add(new Integer(VALUECONCEPT)); } else if (sForCons.equals("interface")) { this.classTypesToCreateConstraintsFor.add(new Integer(MIXIN)); } else if (sForCons.equals("basictype")) { this.classTypesToCreateConstraintsFor.add(new Integer(BASICTYPE)); } else if (sForCons.equals("adeelement")) { this.classTypesToCreateConstraintsFor.add(new Integer(FEATURE)); } else if (sForCons.equals("featuretype")) { this.classTypesToCreateConstraintsFor.add(new Integer(FEATURE)); } else if (sForCons.equals("type")) { this.classTypesToCreateConstraintsFor.add(new Integer(OBJECT)); } else { this.classTypesToCreateConstraintsFor.add(new Integer(UNKNOWN)); } } } } String constraintCreationForProperties = parameter("constraintCreationForProperties"); if (constraintCreationForProperties != null) { if (constraintCreationForProperties.trim().equalsIgnoreCase("false")) { this.constraintCreationForProperties = false; } } /* * TODO add documentation */ String ignoreEncodingRuleTaggedValues = parameter("ignoreEncodingRuleTaggedValues"); if (ignoreEncodingRuleTaggedValues != null) { if (ignoreEncodingRuleTaggedValues.trim().equalsIgnoreCase("true")) { this.ignoreEncodingRuleTaggedValues = true; } } String useStringInterning_value = parameter(PARAM_USE_STRING_INTERNING); if (useStringInterning_value != null && useStringInterning_value.trim().equalsIgnoreCase("true")) { this.useStringInterning = true; } String loadGlobalIds_value = this.parameter(PARAM_LOAD_GLOBAL_IDENTIFIERS); if (loadGlobalIds_value != null && loadGlobalIds_value.trim().equalsIgnoreCase("true")) { this.loadGlobalIds = true; } String language_value = inputConfig.getParameters().get(PARAM_LANGUAGE); if (language_value != null && !language_value.trim().isEmpty()) { this.language = language_value.trim().toLowerCase(); } } catch (SAXException e) { String m = e.getMessage(); if (m != null) { throw new ShapeChangeAbortException( "Error while loading configuration file: " + System.getProperty("line.separator") + m); } else { e.printStackTrace(System.err); throw new ShapeChangeAbortException("Error while loading configuration file: " + System.getProperty("line.separator") + System.err); } } catch (IOException e) { String m = e.getMessage(); if (m != null) { throw new ShapeChangeAbortException( "Error while loading configuration file: " + System.getProperty("line.separator") + m); } else { e.printStackTrace(System.err); throw new ShapeChangeAbortException("Error while loading configuration file: " + System.getProperty("line.separator") + System.err); } } MapEntry nsme = namespace("gml"); if (nsme != null) { GML_NS = nsme.rule; } }
From source file:com.vmware.identity.idm.client.TenantManagementTest.java
private void loadFileAndvalidate(CasIdmClient idmClient, String fileName) throws Exception { //Parse the output file and validate DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setNamespaceAware(true); DocumentBuilder builder = builderFactory.newDocumentBuilder(); builder.setErrorHandler(new SamlParserErrorHandler()); Document outputReadDoc = builder.parse(new FileInputStream(fileName)); idmClient.samlValidate(outputReadDoc); }
From source file:com.vmware.identity.idm.client.TenantManagementTest.java
@TestOrderAnnotation(order = 6) @Test//from w ww . ja v a2 s. com public void testImportTenantSPConfiguration() throws Exception, IDMException { CasIdmClient idmClient = getIdmClient(); try { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setNamespaceAware(true); DocumentBuilder builder = builderFactory.newDocumentBuilder(); builder.setErrorHandler(new SamlParserErrorHandler()); Document tenantNoSLODoc = builder.parse(getClass().getResourceAsStream("/vcd-noSLO.xml")); Document tenantDoc = builder.parse(getClass().getResourceAsStream("/vcd.xml")); IdmClientTestUtil.ensureTenantExists(idmClient, _impTenantName); idmClient.importTenantConfiguration(_impTenantName, tenantNoSLODoc); idmClient.importTenantConfiguration(_impTenantName, tenantDoc); } catch (Exception e) { throw new AssertionError(e); } }
From source file:com.vmware.identity.idm.client.TenantManagementTest.java
@Ignore("bugzilla#1173915 - this seems to require native ad ...also importTenantConfiguration is nolonger support backing up idp configuration via xml") @TestOrderAnnotation(order = 5)// w w w . j a v a2s . c om @Test public void testImportTenantConfiguration() throws Exception, IDMException { // NOTE: this test reads xml metadata from saml-metadata-test.xml file // within client/test/resources // This file has a ValidUntil setting and if this test fails, one of the // possibilities is that this file has expired. Checking ValidUntil element // within that file might be a good idea. CasIdmClient idmClient = getIdmClient(); boolean newTenant = false; try { DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setNamespaceAware(true); DocumentBuilder builder = builderFactory.newDocumentBuilder(); builder.setErrorHandler(new SamlParserErrorHandler()); Document tenantDoc = builder.parse(getClass().getResourceAsStream(_impTenantConfigFile)); //Test importing to a non existing tenant. IdmClientTestUtil.ensureTenantDoesNotExist(idmClient, _impTenantName); try { idmClient.importTenantConfiguration(_impTenantName, tenantDoc); } catch (NoSuchTenantException e) { //expected } //Test setting a existing tenant. newTenant = true; Tenant newtenant = new Tenant(_impTenantName); idmClient.addTenant(newtenant, DEFAULT_TENANT_ADMIN_NAME, DEFAULT_TENANT_ADMIN_PASSWORD.toCharArray()); idmClient.importTenantConfiguration(_impTenantName, tenantDoc); try { Tenant tenant = idmClient.getTenant(_impTenantName); Assert.assertNotNull(tenant); } catch (NoSuchTenantException ex) { Assert.fail("tenant should exists, should not reach here"); } } catch (Exception e) { if (newTenant) { //clean up partial importing. IdmClientTestUtil.ensureTenantDoesNotExist(idmClient, _impTenantName); } throw new AssertionError(e); } }
From source file:com.vmware.identity.idm.client.TenantManagementTest.java
@TestOrderAnnotation(order = 3) @Test/* w w w. j a va 2 s . co m*/ public void testImportExportExternalIDPConfiguration() throws Exception, IDMException { CasIdmClient idmClient = getIdmClient(); Properties props = getTestProperties(); DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setNamespaceAware(true); DocumentBuilder builder = builderFactory.newDocumentBuilder(); builder.setErrorHandler(new SamlParserErrorHandler()); Document externalIDPDoc = builder.parse(getClass().getResourceAsStream(_impExternalIDPConfigFile)); Document externalIDPNoSLODoc = builder .parse(getClass().getResourceAsStream(_impExternalIDPNoSLOConfigFile)); IdmClientTestUtil.ensureTenantExists(idmClient, _impTenantName); //get the certificates in order and key to setup the tenant's credentials String password = props.getProperty(CFG_KEY_STS_KEYSTORE_PASSWORD); KeyStore ks = loadKeyStore(CFG_KEY_STS_KEYSTORE, CFG_KEY_STS_KEYSTORE_PASSWORD); Certificate certForPrivKeyEntry = ks.getCertificate(props.getProperty(CFG_KEY_STS_KEY_ALIAS)); Certificate certAlias1 = ks.getCertificate(props.getProperty(CFG_KEY_STS_KEY_ALIAS1)); PrivateKey key = (PrivateKey) ks.getKey(props.getProperty(CFG_KEY_STS_KEY_ALIAS), password.toCharArray()); idmClient.setTenantCredentials(_impTenantName, Arrays.asList(certForPrivKeyEntry, certAlias1), key); String importedEntityId = null; try { //import importedEntityId = idmClient.importExternalIDPConfiguration(_impTenantName, externalIDPNoSLODoc); importedEntityId = idmClient.importExternalIDPConfiguration(_impTenantName, externalIDPDoc); Collection<IDPConfig> idpConfigs = idmClient.getAllExternalIdpConfig(_impTenantName); Assert.assertEquals(idpConfigs.size(), 1); //export // include optional data for external IDPs Document castleAsSPProfileDoc = idmClient.exportExternalIDPFederation(_impTenantName, true); persistDoc(castleAsSPProfileDoc, _expCastleAsSPProfileFile); loadFileAndvalidate(idmClient, _expCastleAsSPProfileFile); // w/o optional data castleAsSPProfileDoc = idmClient.exportExternalIDPFederation(_impTenantName, false); persistDoc(castleAsSPProfileDoc, _expCastleAsSPProfileFileNoOptionalExternalIDPData); loadFileAndvalidate(idmClient, _expCastleAsSPProfileFileNoOptionalExternalIDPData); } finally { //cleanup, note that any partial import has been clean up by the import API if (null != importedEntityId) { idmClient.removeExternalIdpConfig(_impTenantName, importedEntityId); } } }
From source file:net.sourceforge.pmd.testframework.RuleTst.java
public RuleTst() { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema;/*from www. j a va 2 s . co m*/ try { schema = schemaFactory.newSchema(RuleTst.class.getResource("/rule-tests_1_0_0.xsd")); dbf.setSchema(schema); dbf.setNamespaceAware(true); DocumentBuilder builder = dbf.newDocumentBuilder(); builder.setErrorHandler(new ErrorHandler() { @Override public void warning(SAXParseException exception) throws SAXException { throw exception; } @Override public void fatalError(SAXParseException exception) throws SAXException { throw exception; } @Override public void error(SAXParseException exception) throws SAXException { throw exception; } }); documentBuilder = builder; } catch (SAXException | ParserConfigurationException e) { throw new RuntimeException(e); } }
From source file:net.ymate.framework.commons.XPathHelper.java
private void __doInit(InputSource inputSource, EntityResolver entityResolver, ErrorHandler errorHandler) throws Exception { DocumentBuilder _builder = documentFactory.newDocumentBuilder(); if (entityResolver != null) { _builder.setEntityResolver(entityResolver); }//ww w.j a va 2s. c o m if (errorHandler != null) { _builder.setErrorHandler(errorHandler); } __path = xpathFactory.newXPath(); __document = _builder.parse(inputSource); }